如何使用C#获取当前活动窗口的标题?

时间:2020-03-06 14:32:57  来源:igfitidea点击:

我想知道如何使用C#来获取当前活动窗口(即具有焦点的窗口)的窗口标题。

解决方案

使用Windows API。调用GetForegroundWindow()。

GetForegroundWindow()将为我们提供活动窗口的句柄(名为hWnd)。

说明文件:
http://msdn.microsoft.com/zh-CN/library/ms633505(VS.85).aspx

在此处查看有关如何使用完整源代码执行此操作的示例:

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注释进行编辑,以获得更好的正确性。

循环遍历Application.Current.Windows []并找到IsActive = true的那个。

如果我们在谈论WPF,请使用:

Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);