Reputation: 65
Win32 programs have an entry parameter HINSTANCE
for the Win32 entry function WinMain()
. When you create your own window, the CreateWindow()
API call needs this parameter.
My first idea in my mind is that this HINSTANCE
should be some unique identify to distinguish different windows belong to different processes. Until recently, in some occasions, I use this HINSTANCE
. Wow! If you open the same Win32 program (EXE) twice, each process has the same HINSTANCE
value.
Later I figured out, it was some resource identifier (memory address) in the process. It's a virtual address for the process which is related to its PE structure in memory.
Now, if I have the two windows' HWND
handles, and I want to check whether the two windows are from the same process, what is the best choice?
Upvotes: 1
Views: 1441
Reputation: 51905
You can use the GetWindowThreadProcessId
function to retrieve the ID of the process that created a window, given that window's HWND
.
Below is a brief C code snippet showing how. We check that the return value of each GetWindowThreadProcessId()
call is not zero (see this answer or this blog by Raymond Chen), to ensure that we have passed valid HWND
handles.
// win1 and win2 are both HWND handles to check...
DWORD proc1, proc2;
if (!GetWindowThreadProcessId(win1, &proc1)) { // Error (invalid HWND?)
//.. error handling
}
if (!GetWindowThreadProcessId(win2, &proc2)) {
//..
}
if (proc1 == proc2) {
// Windows created by same process
}
else {
// Windows created by different processes
}
Upvotes: 1