Get all windows

By | March 15, 2020

Long time ago I mean begining of nineties of the last century I started GUI Windows programming. The first application was based on message loop with 3 main players: GetMessage, TranslateMessage, DispatchMessage. Later higher level graphical interface API such as MFC did not require to write the code of Windows message loop, but application can still explicitly sent and received Windows messages, however it looks awkward like pinvoke in c#.
Below is my old code which demonstrates how to get of all windows similar as Spy++ does.


#include <iostream>
#include <windows.h>
#include <Commctrl.h>
void GetChildern(HWND hwnd, DWORD dwProcessId);
int main()
{
   TCHAR szBufferTitle[256];
   DWORD dwProcessId;
   std::cout << “The list of windows.\n”;
   HWND hwnd = ::GetForegroundWindow();
   hwnd = ::GetWindow(hwnd, GW_HWNDFIRST);
   int err = GetLastError();
   while (hwnd != 0) {
      SendMessage(hwnd, WM_GETTEXT, 255, (LPARAM)szBufferTitle);
      GetWindowThreadProcessId(hwnd, &dwProcessId);
      HWND hwndParent = ::GetParent(hwnd);
      wprintf(L”HWND=0x%x, Parent HWND=0x%x ProcessId=%d, Title=%s\n”, (int)hwnd, (int)hwndParent, dwProcessId, szBufferTitle);
      GetChildern(hwnd, dwProcessId);
      hwnd = ::GetWindow(hwnd, GW_HWNDNEXT);
   }
}
void GetChildern(HWND hwnd, DWORD dwProcessId)
{
   TCHAR szBufferTitle[256];
   HWND hwndChild = GetWindow(hwnd, GW_CHILD);
   while (hwndChild)
   {
      SendMessage(hwndChild, WM_GETTEXT, 255, (LPARAM)szBufferTitle);
      wprintf(L”HWND=0x%x, Parent HWND=0x%x ProcessId=%d, Title=%s\n”, (int)hwndChild, (int)hwnd, dwProcessId, szBufferTitle);
      GetChildern(hwndChild, dwProcessId);
      hwndChild = GetWindow(hwndChild, GW_HWNDNEXT);
   }
}


The output is very long, so it is its fragment:


HWND=0x380260, Parent HWND=0x0 ProcessId=16164, Title=GDI+ Window
HWND=0x310206, Parent HWND=0x380260 ProcessId=16164, Title=Default IME
HWND=0x1305c4, Parent HWND=0x0 ProcessId=16164, Title=
HWND=0x1b0c00, Parent HWND=0x0 ProcessId=16164, Title=MediaContextNotificationWindow
HWND=0x5904f0, Parent HWND=0x0 ProcessId=16164, Title=SystemResourceNotifyWindow
HWND=0x5713b4, Parent HWND=0x390c5e ProcessId=16164, Title=ApplicationDesignerWindowPaneControl
HWND=0xfe0da0, Parent HWND=0x5713b4 ProcessId=16164, Title=AppDesigner+RDPWindowsRC
HWND=0x31008fc, Parent HWND=0xfe0da0 ProcessId=16164, Title=HostingPanel
HWND=0x2403e4, Parent HWND=0x31008fc ProcessId=16164, Title=Debug page:
HWND=0xd51bfc, Parent HWND=0x2403e4 ProcessId=16164, Title=PageHostingPanel
HWND=0x880d30, Parent HWND=0xd51bfc ProcessId=16164, Title=Debug
HWND=0x5f0d26, Parent HWND=0x880d30 ProcessId=16164, Title=DesignerWindowPaneBase View

Leave a Reply

Your email address will not be published. Required fields are marked *