简体   繁体   中英

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?

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 .

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM