pigiuz
pigiuz

Reputation: 192

How to get a DLL loading process handle

I'm trying to get the handle to the process which loaded a dll from the dll.

My approach is: in DLL_PROCESS_ATTACH I call EnumWindows(EnumWindowsProc,NULL);

my EnumWindowsProc implementation is the following:

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
    if(GetCurrentProcessId() == GetWindowThreadProcessId(hWnd,NULL)){
        MessageBox(hWnd,L"I loaded your dll!",L"it's me",MB_OK);
        return TRUE;
}
    return FALSE;
}

the problem is that GetCurrentProcessId() == GetWindowThreadProcessId(hWnd,NULL) is never true (if i place the messagebox call outside the if block everything works but it gets called once for every listed window).

Is there any other way to get to the point? Is this approach totally wrong or am I just missing something?

Thanx in advance

Upvotes: 0

Views: 9076

Answers (4)

Aaron Klotz
Aaron Klotz

Reputation: 11585

Use GetCurrentProcess, which returns a pseudo-handle to the current process. If you need a real handle, pass in the pseudo-handle to DuplicateHandle.

Note that it is very dangerous to do too much in DllMain. Calling anything other than KERNEL32 functions is quite dangerous, and even then there are some KERNEL32 functions that you shouldn't be calling. See the DllMain documentation, this document, and several blog posts from Microsoft developers recommending against doing too much in DllMain.

Upvotes: 4

Martin Rosenau
Martin Rosenau

Reputation: 18521

You made a mistake:

GetWindowThreadProcessId does not return the process ID but the thread ID.

Your program must be written like this:

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
    DWORD process;
    GetWindowThreadProcessId(hWnd,&process);
    if(GetCurrentProcessId() == process){
        MessageBox(hWnd,L"I loaded your dll!",L"it's me",MB_OK);
        return TRUE;
    }
    return FALSE;
}

Upvotes: 0

ntcolonel
ntcolonel

Reputation: 900

Try calling GetProcessHandleFromHwnd().

Upvotes: 0

monoceres
monoceres

Reputation: 4770

Easiest way would be to simply use GetCurrentProcess whenever you need the handle.

Upvotes: 2

Related Questions