我想知道如何使用C#获取当前活动窗口(即具有焦点的窗口)的Window标题。
答案 0 :(得分:155)
请参阅示例,了解如何使用完整源代码执行此操作:
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发表评论以获得更好的正确性。
答案 1 :(得分:17)
如果您在谈论WPF,请使用:
Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
答案 2 :(得分:4)
使用Windows API。致电GetForegroundWindow()
。
GetForegroundWindow()
将为您提供活动窗口的句柄(名为hWnd
)。
答案 3 :(得分:4)
循环Application.Current.Windows[]
并找到IsActive == true
。
答案 4 :(得分:1)
基于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字符。
答案 5 :(得分:0)
如果您需要来自MDI应用程序的 当前活动表格 :( MDI-多文档界面)。
Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;