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.
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 ...
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With