How does GetModuleHandle work in Visual c++
Solution 1
You can only call GetModuleHandle(L"C:\\Users\\Steve\\Desktop\\stub.exe");
when you're running C:\Users\Steve\Desktop\stub.exe
.
But in general, you don't call GetModuleHandle
for your EXE name. Since there's only one EXE per process, you just call GetModuleHandle(0)
.
Solution 2
Firstly, GetModuleHandle
requires that you load the dll into the process before hand.
Windows has specific paths that it uses to search for modules, as well as some switches to force 'safe' dll loading, you may want to look into SetDllDirectory
and AddDllDirectory
if you wish to expand the locations searched. See this for an explanation of how Windows search for binaries.
Steve Quezadas
Updated on June 09, 2022Comments
-
Steve Quezadas almost 2 years
I am new to c++ and this code always returns NULL even though i know the file exists:
HMODULE hModule = GetModuleHandle(TEXT("C:\\Users\\Steve\\Desktop\\stub.exe"));
Interestingly, if i copy stub.exe to C:\Windows\system32, it finds the module with this code:
HMODULE hModule = GetModuleHandle(TEXT("stub.exe"));
Am i missing something incredibly basic?
-
Don Reba almost 13 yearsAn EXE can export functions and be linked with just as well as a DLL. It is not a common case, but still a possibility.
-
SSpoke almost 4 years
GetModuleHandle(0)
will return the PE of the current DLL you are currently in, not the parent EXE.. so its not a useful function for this purpose.. I also have this problem. I think you have to useGetCurrentProcess()
-
Bja almost 3 yearsActually
GetModuleHandle(0)
will return a handle to the .exe. Copied directly from MSDN "If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file)." Unless Microsoft has changed the documentation recently. -
MSalters almost 3 years@Bja: No change, this has been the case since Win32. How would the OS even know which DLL made the
GetModuleHandle(0)
call? -
Bja almost 3 years@MSalters: My comment was actually in response to SSpoke, who seems to have the wrong idea of how it actually works. They were the ones that stated
GetModuleHandle(0)
returns the DLL instance you are currently in, not me. I know MS hasn't changed the documentation or changed how the function works, I am not one to reply to a year old comment saying "you are wrong" when after that time no one else has. I should have changed my last line to " Unless Microsoft has changed the documentation recently (which I highly doubt)". Never mind, I now understand it is in regards to a linked EXE.