Younth
Younth

Reputation: 65

How to identify the window is belong to a specific process?

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

Answers (3)

Adrian Mole
Adrian Mole

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

Asker
Asker

Reputation: 1715

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.

Upvotes: 0

Younth
Younth

Reputation: 65

GetWindowThreadProcessId can do the work. Record here.

Upvotes: 0

Related Questions