c# - 获取焦点窗口名称

标签 c# window focus

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

[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;
}

我已经检查过,GetForegroundWindow() 返回的句柄是正确的。但 GetWindowText() 始终返回 null 或负值。

最佳答案

您需要获取文本的长度

[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;
}

关于c# - 获取焦点窗口名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23893375/

相关文章:

javascript - focus() jQuery 函数在 Safari 中不起作用,但在所有其他浏览器上都能正常工作?

c# - 锁定跨多个线程使用的对象中的关键部分

c# - C# 和 C 程序之间的命名管道通信失败

javascript - 如何使用 javascript 移动窗口在计算机屏幕上的位置?

c - OpenGL 窗口错误

Delphi 7 - 处理表单中嵌入框架的 MouseWheel 事件?

c# - 当不能简单地重载时混合可选参数和参数

c# - C# 真的适用于现代网络套接字服务器吗?

css - 模态窗口 javascript css 覆盖

emacs - 如何在emacs中的缓冲区上获得焦点跟随鼠标?