问题描述
当我尝试使用 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 命令提示符,但我需要使用命令提示符。有什么解决办法吗,还是我做错了什么?
解决方法
您将无效的 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();
}