Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetModuleHandle(NULL) vs hInstance

When programming using the Windows API, I've always made the HINSTANCE from WinMain a global variable immediately. If I want to make an OK button, I'd do it like so (given global HINSTANCE g_hInstance):

return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, g_hInstance, NULL); 

but lately I've been seeing the instance handle determined without having to be passed as a parameter or clogging up the global namespace, using a call to GetModuleHandle(NULL)*. So, the example above would look like this:

return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, GetModuleHandle(NULL), NULL); 

*If your compiler supports it, you can write GetModuleHandle(nullptr) and the statement will have the same result.

What's the advantage (if any) of calling GetModuleHandle(NULL) over explicitly specifying the instance handle?

Fine Print: I know this has an answer, but it has not been phrased as its own question on StackOverflow.

like image 900
Proxy Avatar asked Feb 12 '14 03:02

Proxy


People also ask

Is Hinstance a pointer?

MSDN explicitly describes it as a pointer (nowadays equivalent to an HMODULE ) to module base address; we know this may have a completely different meaning for 16 bit applications but in 32/64 bits world each process has its own address space then its exact value is useless, probably always the same for each instance ...

What is GetModuleHandle?

The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. However, if this handle is passed to the FreeLibrary function, the reference count of the mapped module will be decremented. Therefore, do not pass a handle returned by GetModuleHandle to the FreeLibrary function.

What is Hmodule?

HMODULE. A handle to a module. The is the base address of the module in memory. HMODULE and HINSTANCE are the same in current versions of Windows, but represented different things in 16-bit Windows.

How do I get a DLL handle?

If you want handle to the dll you either have to call GetModuleHandle passing the dll's name as the argument (instead of NULL) or you could save the HINSTANCE handle from the DllMain function.


1 Answers

In an EXE, it does not make any difference. hInstance from WinMain() and GetModuleHandle(NULL) both refer to the same HINSTANCE (the module of the .exe file). But it does make a difference if you are creating windows inside of a DLL instead, since you have to use the DLL's hInstance but GetModuleHandle(NULL) will still return the HINSTANCE of the EXE that loaded the DLL.

like image 184
Remy Lebeau Avatar answered Oct 05 '22 03:10

Remy Lebeau