我想知道如何使用C#获取当前活动窗口(即具有焦点的窗口)的窗口标题。
可以在这里查看完整源代码的示例:
http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
根据@Doug McClean的评论进行修改以提高正确性。
System.Runtime.InteropServices;
并确定放置 DllImport 和 static extern 行的位置。将它们粘贴到类中即可。 - barlop如果您在谈论WPF,则使用:
Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
根据GetForegroundWindow function | Microsoft Docs:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);
private string GetCaptionOfActiveWindow()
{
var strTitle = string.Empty;
var handle = GetForegroundWindow();
// Obtain the length of the text
var intLength = GetWindowTextLength(handle) + 1;
var stringBuilder = new StringBuilder(intLength);
if (GetWindowText(handle, stringBuilder, intLength) > 0)
{
strTitle = stringBuilder.ToString();
}
return strTitle;
}
它支持UTF8字符。
循环遍历Application.Current.Windows[]
并找到IsActive == true
的窗口。
GetForegroundWindow()
函数。
GetForegroundWindow()
将返回当前活动窗口的句柄(命名为hWnd
)。
Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;
你可以使用Process类,它非常容易。 使用这个命名空间
using System.Diagnostics;
如果你想要创建一个按钮来获取当前活动窗口。
private void button1_Click(object sender, EventArgs e)
{
Process currentp = Process.GetCurrentProcess();
TextBox1.Text = currentp.MainWindowTitle; //this textbox will be filled with active window.
}