windowswinapicreatewindow

How to draw image on a window?


I have created a window with createwindow() api using VS2005 in C++ on Windows Vista

My requirement is to draw an image (of any format) on that window. I am not using any MFC in this application.


Solution

  • not exactly sure what is your problem: draw a bitmap on the form, or you would like know how to work with various image formats, or both. Anyways below is an example of how you could load a bitmap and draw it on the form:

    HBITMAP hBitmap = NULL;
    
    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
        int wmId, wmEvent;
    
        switch (message)
        {
    <...>
    
        case WM_CREATE:
            hBitmap = (HBITMAP)LoadImage(hInst, L"c:\\test.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
            break;
        case WM_PAINT:
            PAINTSTRUCT     ps;
            HDC             hdc;
            BITMAP          bitmap;
            HDC             hdcMem;
            HGDIOBJ         oldBitmap;
    
            hdc = BeginPaint(hWnd, &ps);
    
            hdcMem = CreateCompatibleDC(hdc);
            oldBitmap = SelectObject(hdcMem, hBitmap);
    
            GetObject(hBitmap, sizeof(bitmap), &bitmap);
            BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);
    
            SelectObject(hdcMem, oldBitmap);
            DeleteDC(hdcMem);
    
            EndPaint(hWnd, &ps);
            break;
        case WM_DESTROY:
            DeleteObject(hBitmap);
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        return 0;
    }
    

    LoadImage loads an icon, cursor, animated cursor, or bitmap. Details here

    For working with various images formats you can use Windows Imaging Component (see IWICBitmapDecoder) or code from here Loading JPEG and GIF pictures or 3rd party tools like FreeImage or LeadTools

    hope this helps, regards