David
David

Reputation: 5537

How to get HINSTANCE to LoadBitmap from resources

I would like to load a bitmap using c++ from resources but I have no idea what hInstance is or how to get it. I have read this but it doesn't help me.

Upvotes: 0

Views: 2471

Answers (1)

Roger Rowland
Roger Rowland

Reputation: 26259

If you're using MFC (you didn't tag your question with MFC but ...) you can use AfxGetInstanceHandle. If you're not using MFC - i.e. you have a standard Winapi implementation), then the instance handle is passed as an argument to your WinMain function.

Creating the boilerplate code for a new Win32 Windows application results in the following code, from which you just need to store hInstance somewhere handy for later

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: Place code here.
    MSG msg;
    HACCEL hAccelTable;

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInstance, IDC_WIN32PROJECT4, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow))
    {
        return FALSE;
    }

    hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32PROJECT4));

    // Main message loop:
    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}

If you'd rather not do that, and you want the HINSTANCE of your exe rather than a DLL, you can also use GetModuleHandle to get the same thing.

HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);

If that's not enough, there is also GetWindowLong

HINSTANCE hInstance = (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE);

Upvotes: 2

Related Questions