views:

127

answers:

3

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
Is that method MFC only?
dicroce
Ya, but I updated with a non MFC way too.
Brian R. Bondy
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
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
Both AfxGetInstanceHandle and GetWindowLong returns HINSTANCE of the application, but you can call AfxGetInstanceHandle without creating a window.
jrbjazz
You could set a global variable if you really wanted to as well and extern it in.
Brian R. Bondy
+3  A: 

If memory serves, GetModuleHandle(NULL); returns the instance handle.

Jerry Coffin
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
@Serge: from what he's saying, the HINSTANCE of the executable is exactly what he wants.
Jerry Coffin
+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
Adrian, how would the code in the library know in which module (exe/dll) it sits?
Serge - appTranslator
+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