How do I get the HMODULE for the currently executing code?

Solution 1:

HMODULE GetCurrentModule()
{ // NB: XP+ solution!
  HMODULE hModule = NULL;
  GetModuleHandleEx(
    GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
    (LPCTSTR)GetCurrentModule,
    &hModule);

  return hModule;
}

Solution 2:

__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://devblogs.microsoft.com/oldnewthing/20041025-00/?p=37483

Solution 3:

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.