获取应用程序的窗口句柄

use*_*526 15 .net c# winapi handle

我正在构建一个应用程序给另一个应用程序mainWindowhandle它收集有关窗口状态的信息.我收集有关子窗口的信息没有问题,但我无法访问应用程序的其他打开窗口甚至菜单.有没有办法获取应用程序的所有窗口句柄?

Tim*_*son 17

您可以执行以下Process.MainWindowHandle操作:使用P/Invoke调用EnumWindows函数,该函数为系统中的每个顶级窗口调用回调方法.

在回调中,调用GetWindowThreadProcessId并比较窗口的进程ID Process.Id; 如果进程ID匹配,则将窗口句柄添加到列表中.


Mez*_*Mez 10

首先,您必须获取应用程序主窗口的窗口句柄.

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

 IntPtr hWnd = (IntPtr)FindWindow(windowName, null);
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此句柄来获取所有子窗口:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);

private List<IntPtr> GetChildWindows(IntPtr parent)  
{  
    List<IntPtr> result = new List<IntPtr>();  
    GCHandle listHandle = GCHandle.Alloc(result);  
    try  
    {  
         EnumWindowProc childProc = new EnumWindowProc(EnumWindow);  
         EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));  
    }  
    finally  
    {  
         if (listHandle.IsAllocated)  
               listHandle.Free();  
    }  
    return result;  
}   
Run Code Online (Sandbox Code Playgroud)

  • EnumWindowProc childProc = new EnumWindowProc(EnumWindow); 这会得到一个错误 (2认同)