我无法解决这个问题。 我得到一个错误:
The name 'hWnd' does not exist in the current context
这听起来很简单,而且可能是……抱歉问了这么明显的问题。
这是我的代码:
public static IntPtr WinGetHandle(string wName)
{
foreach (Process pList in Process.GetProcesses())
{
if (pList.MainWindowTitle.Contains(wName))
{
IntPtr hWnd = pList.MainWindowHandle;
}
}
return hWnd;
}
我尝试了很多不同的方法,但都失败了。 提前致谢。
最佳答案
更新:参见 Richard's Answer更优雅的方法。
不要忘记您在循环内声明您 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
或者以更符合 LINQ 的方式....
IntPtr? handle = Process
.GetProcesses()
.SingleOrDefault(x => x.MainWindowTitle.Contains(wName))
?.Handle;
return handle.HasValue ? handle.Value : IntPtr.Zero
关于c# - 按名称/标题返回窗口句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547639/