2009-05-04 61 views
13

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

+0

看看这个工作的解决方案:http://stackoverflow.com/a/28055461/1274092 – 2015-01-20 21:30:01

回答

15

你可以做Process.MainWindowHandle似乎要做的事情:使用P/Invoke调用EnumWindows函数,该函数为系统中的每个顶级窗口调用回调方法。

在您的回拨中,拨打GetWindowThreadProcessId,并将窗口的进程ID与Process.Id进行比较;如果进程ID匹配,则将窗口句柄添加到列表中。

8

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

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

IntPtr hWnd = (IntPtr)FindWindow(windowName, null); 

然后,您可以使用该句柄来获取所有childwindows:

[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; 
} 
+0

梅茨问题ISN”我可以很容易地做到这一点,我不能做的是除了mainWindow和它的孩子以外的其他窗口... – user361526 2009-05-05 14:19:49

+0

这适用于任何窗口,也适用于不属于自己的应用程序的窗口。对不起,如果我误解了你的问题。 – Mez 2009-05-05 18:56:33

+0

从哪里来'EnumWindowProc'? – 2017-05-18 22:12:44