2009-05-04 59 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