GetModuleHandle()
requires the DLL to already be loaded:
Retrieves a module handle for the specified module. The module must have been loaded by the calling process.
ntdll.dll will always be loaded but user32.dll and advapi32.dll are not necessarily loaded by default. Based on your description it sounds as though the code calls GetModuleHandle()
first, which will fail if the DLL is not already loaded (check the value of GetLastError()
in the event of failure).
Use LoadLibrary()
for DLLs that are not loaded by default. However, using LoadLibrary()
in the event that GetModuleHandle()
fails is a dangerous strategy as some other thread in the process could FreeLibrary()
the DLL that you have acquired a handle to via GetModuleHandle()
(meaning any function addresses that you have acquired via that handle are invalid as the DLL is no longer in memory). Using LoadLibrary()
, with the subsequent FreeLibrary()
, is a safer approach as it ensures the DLL won't be unloaded until you FreeLibrary()
it.