The HINSTANCE
of a win32 application is passed to WinMain
, but is there any other way of determining the current HINSTANCE
(in case you couldn't tell, I'm very new to win32 programming!)? I need to create a window inside of a library and (since the library is cross platform), I'd prefer not to have to pass it in.
Determine the current HINSTANCE?
If memory serves, GetModuleHandle(NULL);
returns the instance handle.
Not totally correct: It reutrns the HINSTANCE of the exe. If the code executes in a DLL, this may lead to wrong behaviours –
Lillie
@Serge: from what he's saying, the HINSTANCE of the executable is exactly what he wants. –
Highoctane
+1: By passing in a module name, that function can be used to get the
HINSTANCE
of DLLs as well. Note that HINSTANCE
and HMODULE
are essentially equivalent in modern versions of Windows. –
Manners Adrian, how would the code in the library know in which module (exe/dll) it sits? –
Lillie
__ImageBase is your friend, especially in the case of libraries.
Note that the linked blog post (by R. Chen, although not the same post as the one linked by Brian Bondy) is worth reading (including the comments!)
Ignoring the cumbersome GetModuleHandleEx with
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, this is really the only reliable way to find the module handle, and it should be the accepted answer. –
Bentham If you are using MFC, you can use AfxGetInstanceHandle.
If you are not using MFC you can use: GetWindowLong(hWnd, GWL_HINSTANCE)
That assumes I already have a window (and thus, and hwnd)... I'm trying to push the job of window creation out to my library... –
Photographer
Please review this link, I think you may run into the problem Raymond is talking about: blogs.msdn.com/oldnewthing/archive/2005/04/18/409205.aspx –
Kumkumagai
Both AfxGetInstanceHandle and GetWindowLong returns HINSTANCE of the application, but you can call AfxGetInstanceHandle without creating a window. –
Handful
You could set a global variable if you really wanted to as well and extern it in. –
Kumkumagai
The
GetWindowLong()
version assumes a 32 bit platform build. But on Win64, you run into trouble. –
Headwaters The function AfxGetStaticModuleState() does the trick. If you call it within a dll, the functions returns the handle to the dll, if the call within a exe it returns the handle to the executable.
DWORD size;
TCHAR fileName [MAX_PATH];
HMODULE hModule = AfxGetStaticModuleState()->m_hCurrentInstanceHandle;
::GetModuleFileName (hModule, fileName, size);
The question is tagged winapi. There is no
AfxGetStaticModuleState
in the Windows API. –
Bentham © 2022 - 2024 — McMap. All rights reserved.
hInstance = NULL
when registering the class and passNULL
toCreateWindow()
and you're good to go. – JarretHINSTANCE
becomes a crucial part in identifying the window class. Details here: What is the HINSTANCE passed to CreateWindow and RegisterClass used for?. – Bentham