简体   繁体   English

C++ Win API - FindWindow() 或 EnumWindows() 检索特定 windows

[英]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):我从特定的 window 检索 window 句柄时遇到以下问题(标题和 class 名称已知):

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.有两个相同的 windows 在两个不同的进程下具有不同的句柄,但是FindWindow()只能从产生的最新 window 中找到句柄,而不是从第一个中找到。

What can be used instead?可以用什么代替? Can EnumWindows() be used to retrieve a list of windows with the same characteristics?可以使用EnumWindows()检索具有相同特征的 windows 列表吗?

Use the Win32 API EnumWindows , and then check which process each window belongs to by using the Win32 API GetWindowThreadProcessId .使用 Win32 API EnumWindows ,然后使用 Win32 API GetWindowThreadProcessId查看每个 window 属于哪个进程。

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 .如果需要查看各个进程的window,可以参考这个答案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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