首页 > 解决方案 > 为什么 GetWindowThreadProcessId 函数不能与命令行一起使用?

问题描述

当我尝试使用 GetWindowThreadProcessId 函数时,它失败并使用 GetLastError 函数并将其转换为字符串,它显示“参数不正确”。它发现窗口很好,我尝试将 HWND 参数更改为打开的 .txt 文件,它似乎工作正常,所以我认为问题出在命令行而不是其他问题。这是我的代码:

HWND win = FindWindowA(NULL, (LPCSTR)"C:\\WINDOWS\\system32\\cmd.exe");
        LPSTR str;
        str = new CHAR[50];
        GetWindowTextA(win, str, 49);
        cout << str;
        LPDWORD * pid;
        pid = new LPDWORD();
        DWORD cmdthread = GetWindowThreadProcessId(win, *pid);
        cout << GetLastErrorAsString();

它似乎适用于任何非 Windows 命令提示符,但我需要使用命令提示符。有什么解决办法还是我做错了什么?

标签: c++windowsprocess

解决方案


您将无效DWORD*指针传递给GetWindowThreadProcessId(). 试试这个:

HWND win = FindWindowA(NULL, "C:\\WINDOWS\\system32\\cmd.exe");
if (win != NULL)
{
    // this part is redundant, since you just did a search for
    // the HWND by its window text, so you already know what
    // the text is...
    char str[50] = {};
    GetWindowTextA(win, str, 49);
    cout << str;
    //

    DWORD pid = 0;
    DWORD tid = GetWindowThreadProcessId(win, &pid);
    if (tid != 0)
        cout << "Thread ID: " << tid << " Process ID: " << pid;
    else
        cout << GetLastErrorAsString();
}

推荐阅读