枚举窗口时出现问题

Issue when enumerating windows

本文关键字:问题 窗口 枚举      更新时间:2023-10-16

我在尝试运行以下代码时遇到问题:

#include "header.h"
int main()
{
    id = GetCurrentProcessId();
    EnumWindows(hEnumWindows, NULL);
    Sleep(5000);
    //MoveWindow(hThis, 450, 450, 100, 100, TRUE);
    system("pause");
    return 0;
}
//header.h
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <Windows.h>
using namespace std;
DWORD id = 0;
HWND hThis = NULL;
BOOL CALLBACK hEnumWindows(HWND hwnd, LPARAM lParam)
{
    DWORD pid = 0;
    pid = GetWindowThreadProcessId(hwnd, NULL);
    if (pid == id)
    {
        hThis = GetWindow(hwnd, GW_OWNER);
        if (!hThis)
        {
            cout << "Error getting window!" << endl;
        }
        else
        {
            char *buffer = nullptr;
            int size = GetWindowTextLength(hThis);
            buffer = (char*)malloc(size+1);
            if (buffer != nullptr)
            {
                GetWindowText(hThis, buffer, size);
                cout << pid << ":" << buffer << endl;
                free(buffer);
            }
        }
    }
    return TRUE;
}

当我运行此代码时,屏幕上不会输出任何内容,就好像程序没有附加一样。我试着在VS2013中的控制台和windows子系统下运行它。

根据GetCurrentProcessId文档,API

检索调用进程的进程标识符。

GetWindowThreadProcessId,另一方面,

检索创建指定窗口的线程的标识符,以及创建该窗口的进程的标识符(可选)。

返回值是创建窗口的线程的标识符。

所以看看你的电话:

pid = GetWindowThreadProcessId(hwnd, NULL);

实际上,你得到的是线程ID,而不是进程ID。所以当你比较pidid时,你比较的是进程ID和线程ID,这是行不通的。试试这个:

GetWindowThreadProcessId(hwnd, &pid);

(注意:我实际上无法测试这是否有效,因为EnumWindows需要一个顶级窗口来枚举,而我将其作为控制台应用程序运行。如果这个答案不适用,请告诉我,我会删除它。)

(作为第二个注意事项,您不需要再使用NULL,即使是像HWND这样的WinAPI。nullptr也可以很好地工作。)

我假设您正试图从ProcessID中找到"Main"窗口。。在这种情况下,这可能会有所帮助:

#include "stdafx.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <Windows.h>
struct WindowHandleStructure
{
    unsigned long PID;
    HWND WindowHandle;
};
BOOL CALLBACK EnumWindowsProc(HWND WindowHandle, LPARAM lParam)
{
    unsigned long PID = 0;
    WindowHandleStructure* data = reinterpret_cast<WindowHandleStructure*>(lParam);
    GetWindowThreadProcessId(WindowHandle, &PID);
    if (data->PID != PID || (GetWindow(WindowHandle, GW_OWNER) && !IsWindowVisible(WindowHandle)))
    {
        return TRUE;
    }
    data->WindowHandle = WindowHandle;
    return FALSE;
}
HWND FindMainWindow(unsigned long PID)
{
    WindowHandleStructure data = { PID, nullptr };
    EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&data));
    return data.WindowHandle;
}
int main()
{
    HWND Window = FindMainWindow(GetCurrentProcessId());
    std::wstring Buffer(GetWindowTextLength(Window) + 1, L'');
    GetWindowText(Window, &Buffer[0], Buffer.size());
    std::wcout << Buffer.c_str() << L"n";
    system("pause");
    return 0;
}