将位图加载到窗口

时间:2015-04-06 12:56:10

标签: c++ c winapi gdi

我想在我的应用程序中将一个位图加载到一个窗口,我将使用GDI将位图绘制到窗口。我是否还应该在处理WM_PAINT消息时绘制位图,以便位图在窗口上持续显示?

1 个答案:

答案 0 :(得分:2)

是的,您应该在 WM_PAINT WM_ERASEBKGND 处理程序中绘制位图,如下所示:

        switch(Msg)
        {
        case WM_DESTROY:
            PostQuitMessage(WM_QUIT);
            break;
        case WM_PAINT:
            hDC = BeginPaint(hWnd, &Ps);

            // Load the bitmap from the resource
            bmp = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_MY_COOL_PIC));
            // Create a memory device compatible with the above DC variable
            MemDC = CreateCompatibleDC(hDC);
            // Select the new bitmap
            HBITMAP hOldBmp = SelectObject(MemDC, bmp);

            // Copy the bits from the memory DC into the current dc
            BitBlt(hDC, 10, 10, 450, 400, MemDC, 0, 0, SRCCOPY);

            // Restore the old bitmap
            SelectObject(MemDC, hOldBmp);
            DeleteObject(bmp);

            DeleteDC(MemDC);
            EndPaint(hWnd, &Ps);
            break;
        default:
            return DefWindowProc(hWnd, Msg, wParam, lParam);
        }