How do I get the HMODULE for the currently executing code?
HMODULE GetCurrentModule()
{ // NB: XP+ solution!
HMODULE hModule = NULL;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)GetCurrentModule,
&hModule);
return hModule;
}
__ImageBase
is a linker generated symbol that is the DOS header of the module (MSVC only). From that you can cast its address to an HINSTANCE
or HMODULE
. So it's more convenient than going through an API.
So you just need to do this:
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase)
From https://web.archive.org/web/20100123173405/http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
I'd look at GetModuleHandleEx()
using the flag GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
. It looks like you can change your GetCurrentModule()
to call this routine instead of VirtualQuery()
, and pass the address of GetCurrentModule()
as the lpModuleName
argument.
ETA:
const HMODULE GetCurrentModule()
{
DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS;
HMODULE hm = 0;
::GetModuleHandleEx( flags, reinterpret_cast<LPCTSTR>( GetCurrentModule ), &hm );
return hm;
}
I didn't try it, but I think that'll do what you want.