I'm building an app that given another app mainWindowhandle it collects information about the window state. I have no problem collecting information about child windows, but I can not access the other open windows of an application or even the menus. Is there any way of getting all window handles of an application?
Asked
Active
Viewed 1e+01k times
3 Answers
17
You could do what Process.MainWindowHandle
appears to do: use P/Invoke to call the EnumWindows
function, which invokes a callback method for every top-level window in the system.
In your callback, call GetWindowThreadProcessId
, and compare the window's process id with Process.Id
; if the process ids match, add the window handle to a list.

Tim Robinson
- 53,480
- 10
- 121
- 138
11
First, you'll have to get the windowhandle of the application's mainwindow.
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
IntPtr hWnd = (IntPtr)FindWindow(windowName, null);
Then, you can use this handle to get all 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;
}

Mez
- 2,817
- 4
- 27
- 29
-
1Mez the problem isn't getting child windows, I can do that easily, what I can't do is get to other windows besides mainWindow and its childs... – user361526 May 05 '09 at 14:19
-
1This works for any window, also for windows not belonging to the own application. Sorry if I misunderstood your question. – Mez May 05 '09 at 18:56
-
1
-
1Add in a declaration for it: private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); – luka Apr 20 '18 at 08:17
-
2EnumWindowProc childProc = new EnumWindowProc(EnumWindow); this get an error – luka Apr 20 '18 at 09:48
3
public void GetWindowHandles()
{
List<IntPtr> windowHandles = new List<IntPtr>();
foreach (Process window in Process.GetProcesses())
{
window.Refresh();
if (window.MainWindowHandle != IntPtr.Zero)
{
windowHandles.Add(window.MainWindowHandle);
}
}
}
Read This as to why we call the refresh method and check if the pointer is zero

Jamisco
- 1,658
- 3
- 13
- 17