1

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Younth
  • 65
  • 6
  • [What is the HINSTANCE passed to CreateWindow and RegisterClass used for?](https://devblogs.microsoft.com/oldnewthing/20050418-59/?p=35873) – IInspectable Apr 03 '21 at 08:42

3 Answers3

1

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
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • "*You can ignore the return value*" - you shouldn't ignore it. At the very least, check it to make sure the function doesn't fail, ie if the HWNDs are no longer valid. – Remy Lebeau Apr 03 '21 at 17:39
  • @Remy OK, code modified according to the info provided in Raymond's blog and in the linked SO answer. – Adrian Mole Apr 03 '21 at 17:52
0

GetWindowThreadProcessId can do the work. Record here.

Younth
  • 65
  • 6
0

An interactive way to do this would be to use Microsoft's Spy++, which lets you find the Process ID, Thread ID, and parents/children of a window by point-and-clicking its GUI.

You can also find window handles (and plenty of other window-specific data) in this way.

Asker
  • 1,299
  • 2
  • 14
  • 31