Determine the current HINSTANCE?

WinapiHinstance

Winapi Problem Overview


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.

Winapi Solutions


Solution 1 - Winapi

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

Solution 2 - Winapi

__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!)

Solution 3 - Winapi

If you are using MFC, you can use AfxGetInstanceHandle.

If you are not using MFC you can use: GetWindowLong(hWnd, GWL_HINSTANCE)

Solution 4 - Winapi

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondicroceView Question on Stackoverflow
Solution 1 - WinapiJerry CoffinView Answer on Stackoverflow
Solution 2 - WinapiSerge WautierView Answer on Stackoverflow
Solution 3 - WinapiBrian R. BondyView Answer on Stackoverflow
Solution 4 - WinapiMarcel MatemanView Answer on Stackoverflow