【问题标题】:Get the focused window name获取焦点窗口名称
【发布时间】:2025-11-29 21:50:01
【问题描述】:

我正在尝试获取当前焦点窗口的名称。感谢我的研究,我有这个代码:

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

private static bool IsFocused(string name)
{
   StringBuilder buffer = new StringBuilder(256);

   if (GetWindowText(GetForegroundWindow(), buffer, buffer.Length + 1) > 0)
   {
      if (buffer.ToString() == name)
      {
         return true;
      }
   }
   return false;
}

我检查过,GetForegoundWindow() 返回的句柄是正确的。但是GetWindowText() 总是返回一个空值或负值。

【问题讨论】:

    标签: c# window focus


    【解决方案1】:

    需要获取文本的长度

    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();
    
    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
    
    [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
    public static extern int GetWindowTextLength(IntPtr hWnd);
    
    private static bool IsFocused(string name)
    {
        var handle = GetForegroundWindow();
        var length = GetWindowTextLength(handle);
        var builder = new StringBuilder(length + 1);
    
        GetWindowText(handle, builder, builder.Capacity);
    
        return builder.ToString() == name;
    }
    

    【讨论】: