通过它的名称/标题返回窗口句柄 [英] Return Window handle by it's name / title

查看:157
本文介绍了通过它的名称/标题返回窗口句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解决不了这个问题。
我得到一个错误:

I can't solve this problem. I get an error:

The name 'hWnd' does not exist in the current context

这听起来很容易,可能是...询问这么明显的问题抱歉。

It sounds very easy and probably is... sorry for asking so obvious questions.

下面是我的代码:

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



我试着用很多不同的方式,每个失败。
先谢谢了。

I tried with many different ways and each fails. Thanks in advance.

推荐答案

不要忘了你,你声明的hWnd 循环中 - 这意味着它是只在循环里可见。如果窗口标题不存在,会发生什么?如果你想用你应该把它声明的外循环,将其设置在循环内,然后返回它...

Don't forget you're declaring you hWnd inside the loop - which means it's only visible inside the loop. What happens if the window title doesn't exist? If you want to do it with a for you should declare it outside your loop, set it inside the loop then return it...

  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

这篇关于通过它的名称/标题返回窗口句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆