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

d4n*_*4nt 107 .net c# windows winforms

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

Jor*_*ira 162

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

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑 @Doug McClean评论更好的正确性.

  • 不要忘记做一个好公民.http://blogs.msdn.com/oldnewthing/archive/2007/07/27/4072156.aspx和http://blogs.msdn.com/oldnewthing/archive/2008/10/06/8969399.aspx有相关信息. (7认同)
  • 一个新的注释,让它运行,`使用System.Runtime.InteropServices;`并重新放置dll导入和静态外部线的位置.在课堂上粘贴它 (3认同)
  • 您链接到的网站不可用。这是(可能)它的网络存档:https://web.archive.org/web/2015081404381​​0/http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-与-windows-api-in-c/ (2认同)
  • 另外,我希望每次前景窗口发生变化时都能通知我的应用程序。有什么活动吗? (2认同)

小智 17

如果你在谈论WPF,那么使用:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
Run Code Online (Sandbox Code Playgroud)


Moh*_*yan 6

基于GetForegroundWindow 函数| 微软文档

[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;
}
Run Code Online (Sandbox Code Playgroud)

它支持 UTF8 字符。


小智 5

循环Application.Current.Windows[]并找到带有 的那个IsActive == true

  • 这不是只适用于当前.Net应用程序中的Windows吗?我认为 d4nt 想要获取桌面上当前活动窗口的标题,无论它属于哪个应用程序。 (13认同)