我无法解决此问题。我收到一个错误:
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;
}
我尝试了许多不同的方法,但每种方法都失败了。预先感谢。
[别忘了您在循环内声明了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
因为您在if块中声明了hWnd
,所以它外面的return语句无法访问它。请参阅http://www.blackwasp.co.uk/CSharpVariableScopes.aspx以进行澄清。
您提供的代码可以通过移动hWnd变量的声明来固定:
public static IntPtr WinGetHandle(string wName)
{
IntPtr hwnd = IntPtr.Zero;
foreach (Process pList in Process.GetProcesses())
{
if (pList.MainWindowTitle.Contains(wName))
{
hWnd = pList.MainWindowHandle;
}
}
return hWnd;
}
作为解决此问题的一种选择:
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public IntPtr GetHandleWindow(string title)
{
return FindWindow(null, title);
}
hWnd
在foreach
循环中声明。 其上下文在foeach
循环内。要获取其值,请在foreach
循环外声明它。
像这样使用它,
public static IntPtr WinGetHandle(string wName){
IntPtr hWnd = NULL;
foreach (Process pList in Process.GetProcesses())
if (pList.MainWindowTitle.Contains(wName))
hWnd = pList.MainWindowHandle;
return hWnd;
}
这晚了几年,但是,正如其他人提到的,hWnd
的范围仅在foreach
循环中。
但是值得注意的是,假设您对该函数不做任何其他事情,那么其他人提供的答案有两个问题:
hWnd
变量实际上是不必要的,因为它仅用于一件事(作为return
的变量)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;
}
#include <windows.h>
#using <System.dll>
using namespace System;
using namespace System::Diagnostics;
using namespace System::ComponentModel;
// get window handle from part of window title
public static IntPtr WinGetHandle(string wName)
{
IntPtr hwnd = IntPtr.Zero;
foreach (Process pList in Process.GetProcesses())
{
if (pList.MainWindowTitle.Contains(wName))
{
hWnd = pList.MainWindowHandle;
return hWnd;
}
}
return hWnd;
}
// get window handle from exact window title
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public IntPtr GetHandleWindow(string title)
{
return FindWindow(null, title);
}