GetModuleHandle function
Overview
Syntax
Parameters
Return Value
Remarks
Example
Retrieves a module handle for the specified module. The module must have been loaded by the calling process.
HMODULE GetModuleHandleA(
LPCSTR lpModuleName
);
HMODULE GetModuleHandleW(
LPCWSTR lpModuleName
);
#ifdef UNICODE
#define GetModuleHandle GetModuleHandleW
#else
#define GetModuleHandle GetModuleHandleA
#endif
| Parameter | Description |
|---|---|
lpModuleName |
The name of the loaded module (either a DLL or an executable).
If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
The name is case-insensitive and can include or omit the file extension.
|
If the function succeeds, the return value is a handle to the specified module.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
- The returned module handle can be used in calls to
GetProcAddress,FreeLibrary, and other module‑related functions. - Do not attempt to free a module handle obtained for the executable file of the current process.
- Use
GetModuleHandleExif you need to retrieve a handle with a specific reference count or to retrieve the handle for a module that is already loaded. - When using the ANSI version (
GetModuleHandleA), the module name is interpreted using the current system code page.
The following example obtains a handle to kernel32.dll and retrieves the address of the LoadLibraryA function.
#include <windows.h>
#include <stdio.h>
int main(void)
{
HMODULE hMod = GetModuleHandleA("kernel32.dll");
if (hMod == NULL) {
printf("GetModuleHandle failed (error %lu)\\n", GetLastError());
return 1;
}
FARPROC proc = GetProcAddress(hMod, "LoadLibraryA");
if (proc == NULL) {
printf("GetProcAddress failed (error %lu)\\n", GetLastError());
return 1;
}
printf("LoadLibraryA address: %p\\n", proc);
return 0;
}