AndreiD
AndreiD

Reputation: 123

C++ Win API - FindWindow() or EnumWindows() to retrieve specific windows

I have the following problem with retrieving the window handle from a specific window (title and class name are known):

There are two identical windows with different handles under two different processes, but FindWindow() can find the handle only from the newest window spawned, never from the first one.

What can be used instead? Can EnumWindows() be used to retrieve a list of windows with the same characteristics?

Upvotes: 1

Views: 2638

Answers (2)

Zeus
Zeus

Reputation: 3890

Use the Win32 API EnumWindows , and then check which process each window belongs to by using the Win32 API GetWindowThreadProcessId.

Here is a sample:

#include <iostream>
#include <Windows.h>
using namespace  std;
BOOL CALLBACK enumProc(HWND hwnd, LPARAM) {
    TCHAR buf[1024]{};

    GetClassName(hwnd, buf, 100);
    if (!lstrcmp(buf, L"Notepad"))
    {
        GetWindowText(hwnd, buf, 100);
        DWORD pid = 0;
        GetWindowThreadProcessId(hwnd, &pid);
        wcout << buf << " " << pid << endl;
    }
    return TRUE;
}

int main() {
    EnumWindows(&enumProc, 0);
}

If you need to check the window of each process, you can refer to this answer.

Upvotes: 4

Devolus
Devolus

Reputation: 22094

typedef struct
{
    const char *name;
    const char *class;
    HWND handles[10];
    int handlesFound;
} SearchWindowInfo;

SearchWindowInfo wi;
wi.handlesFound = 0;
wi.title = "WindowName";
wi.class = "ClassName";

BOOL CALLBACK searchWindowCallback(HWND hwnd, LPARAM lParam)
{
    SearchWindoInfo *wi = (SearchWindoInfo *)lParam;
    char buffer[256];

    if (wi->handlesFound == 10)
        return FALSE;
    
    buffer[255] = 0;
    if (wi->name)
    {
        int rc = GetWindowText(hwnd, buffer, sizeof(buffer)-1);
        if(rc)
        {
            if (strcmp(wi->name, buffer) == 0)
            {
                wi->handles[wi->handlesFound++] = hwnd;
                return TRUE;
            }
        }
    }

    if (wi->class)
    {
        int rc = GetClassName (hwnd, buffer, sizeof(buffer)-1);
        if(rc)
        {
            if (strcmp(wi->class, buffer) == 0)
            {
                wi->handles[wi->handlesFound++] = hwnd;
                return TRUE;
            }
        }
    }

    return TRUE;
}

EnumWindows(searchWindowCallback, (LPARAM)&wi);
for(int i = 0; i < wi.handlesFound; i++)
{
    // yeah...
}

Upvotes: 2

Related Questions