c++ - 枚举窗口时出现问题

标签 c++ windows winapi

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

#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 docs , 应用程序接口(interface)

Retrieves the process identifier of the calling process.

GetWindowThreadProcessId ,另一方面,

Retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window.

The return value is the identifier of the thread that created the window.

所以看看你的电话:

pid = GetWindowThreadProcessId(hwnd, NULL);

您实际上得到的是线程 ID,而不是进程 ID。因此,当您将 pidid 进行比较时,您是在比较进程 ID 和线程 ID,这是行不通的。试试这个:

GetWindowThreadProcessId(hwnd, &pid);

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

(作为第二个注意事项,您不再需要使用 NULL,即使对于像 HWND 这样的 WinAPI 东西也是如此。nullptr 将起作用非常好。)

关于c++ - 枚举窗口时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22924627/

相关文章:

windows - 无法将 unicode .csv 读入 R

windows - 以编程方式或从 Windows 中的命令行显示文件属性对话框

regex - grep 正则表达式搜索数字序列

c++ - 从 C DLL 调用重载的 C++ 函数

c++ - 传递并调用一个成员函数(boost::bind/boost::function?)

c++ - CUDA/开放式;将分支重写为非分支表达式

c++ - 让编译器在 Notepad++ 中工作

c# - SendMessage WM_SETTEXT 到另一个进程失败,因为目标进程中接收到的指针已更改

c++ - 编辑获得焦点时清除文本

c++ - 我是否在简单的 OpenMP for 循环中误用了引用变量,还是 clang 错误?