返回窗口句柄的名称/标题

Vix*_*inG 13 c# window handle title

我无法解决这个问题.我收到一个错误:

The name 'hWnd' does not exist in the current context
Run Code Online (Sandbox Code Playgroud)

这听起来很容易,可能是...对于提出如此明显的问题感到抱歉.

这是我的代码:

    public static IntPtr WinGetHandle(string wName)
    {
        foreach (Process pList in Process.GetProcesses())
        {
            if (pList.MainWindowTitle.Contains(wName))
            {
                IntPtr hWnd = pList.MainWindowHandle;
            }
        }
        return hWnd;
    }
Run Code Online (Sandbox Code Playgroud)

我尝试了许多不同的方法,每个都失败了.提前致谢.

Bas*_*sic 16

不要忘记你在hWnd循环中声明你- 这意味着它只在循环中可见.如果窗口标题不存在会发生什么?如果你想用它来做它for你应该在循环之外声明它,在循环中设置它然后返回它...

  IntPtr hWnd = IntPtr.Zero;
  foreach (Process pList in Process.GetProcesses())
  {
      if (pList.MainWindowTitle.Contains(wName))
      {
          hWnd = pList.MainWindowHandle;
      }
  }
  return hWnd; //Should contain the handle but may be zero if the title doesn't match
Run Code Online (Sandbox Code Playgroud)

  • 它不能为null,因为`无法将null转换为'System.IntPtr',因为它是一个不可为空的值类型 (2认同)

Wiz*_*ard 9

作为解决此问题的一个选项:

[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

public IntPtr GetHandleWindow(string title)
{
    return FindWindow(null, title);
} 
Run Code Online (Sandbox Code Playgroud)


Ric*_*ard 7

虽然晚了几年,但正如其他人提到的,范围hWnd仅在foreach循环中。

然而值得注意的是,假设您没有对该函数执行任何其他操作,则其他人提供的答案存在两个问题:

  1. 该变量hWnd实际上是不必要的,因为它仅用于一件事(作为 的变量return
  2. foreach循环效率低下,因为即使在找到匹配项之后,您仍会继续搜索其余进程。事实上,它会返回它找到的最后一个匹配的进程。

假设您不想匹配最后一个进程(第 2 点),那么这是一个更干净、更高效的函数:

public static IntPtr WinGetHandle(string wName)
{
    foreach (Process pList in Process.GetProcesses())
        if (pList.MainWindowTitle.Contains(wName))
            return pList.MainWindowHandle;

    return IntPtr.Zero;
}
Run Code Online (Sandbox Code Playgroud)