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), id prefer not to have to pass it in.
A:
If you are using MFC, you can use AfxGetInstanceHandle.
If you are not using MFC you can use: GetWindowLong(hWnd, GWL_HINSTANCE)
Brian R. Bondy
2009-11-17 16:20:20
Is that method MFC only?
dicroce
2009-11-17 16:21:41
Ya, but I updated with a non MFC way too.
Brian R. Bondy
2009-11-17 16:23:35
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...
dicroce
2009-11-17 16:25:21
Please review this link, I think you may run into the problem Raymond is talking about: http://blogs.msdn.com/oldnewthing/archive/2005/04/18/409205.aspx
Brian R. Bondy
2009-11-17 16:29:39
Both AfxGetInstanceHandle and GetWindowLong returns HINSTANCE of the application, but you can call AfxGetInstanceHandle without creating a window.
jrbjazz
2009-11-17 16:37:28
You could set a global variable if you really wanted to as well and extern it in.
Brian R. Bondy
2009-11-17 16:48:59
+3
A:
If memory serves, GetModuleHandle(NULL);
returns the instance handle.
Jerry Coffin
2009-11-17 16:33:24
Not totally correct: It reutrns the HINSTANCE of the exe. If the code executes in a DLL, this may lead to wrong behaviours
Serge - appTranslator
2009-11-17 16:38:31
@Serge: from what he's saying, the HINSTANCE of the executable is exactly what he wants.
Jerry Coffin
2009-11-17 16:40:24
+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.
Adrian McCarthy
2009-11-17 16:47:03
Adrian, how would the code in the library know in which module (exe/dll) it sits?
Serge - appTranslator
2009-11-17 20:13:20
+3
A:
__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!)
Serge - appTranslator
2009-11-17 16:36:21