GetWindowThreadProcessId Exhibits Weird Behavior

I wrote a program that calls GetWindowThreadProcessId. This function will either return a DWORD with the process ID if the second argument is NULL, or the second argument can be a pointer to a DWORD that the process ID is written to. When I call this function, different values are written to the PID variable depending on whether or the second argument is a pointer, or the other technique is used. May someone please explain this weird behavior?



[ code]
#include <iostream>
#include <Windows.h>

int main()
{
HWND hWnd;
DWORD PID;
HANDLE hProc;

hWnd = FindWindow(NULL, L"Untitled - Notepad");

if (!hWnd)
{
std::cout << "Failed to find window" << std::endl;
return 0;
}

PID = GetWindowThreadProcessId(hWnd, NULL);
std::cout << PID << std::endl;
GetWindowThreadProcessId(hWnd, &PID);
std::cout << PID << std::endl;

if (!PID)
{
std::cout << "Failed to get process ID" << std::endl;
return 0;
}

hProc = OpenProcess(PROCESS_ALL_ACCESS, TRUE, PID);

if (!hProc)
{
std::cout << "Failed to oppen the process." << std::endl;
return 0;
}

std::cout << "Success!" << std::endl;

return 0;
}
[ /code]
https://msdn.microsoft.com/en-us/library/windows/desktop/ms633522%28v=vs.85%29.aspx

According to this, GetWindowThreadProcessId() returns the thread id, not process id. The second argument can receive the process id.
Last edited on
Yes, ahcfan is right. Call should look more like this:
1
2
3
4
5
DWORD tID, pID;
tID = GetWindowThreadProcessId(hWnd,&pID);

cout << "Thread ID: " << tID << endl;
cout << "Process ID: " << pID << endl;
OK, thanks. I really should skim less.
Topic archived. No new replies allowed.