首页 > 解决方案 > 由 CreateCompatibleBitmap 创建的 HBITMAP 是黑白的

问题描述

我读过一篇关于后缓冲的文章,我通过以下方式重新创建了这篇文章:

void paint(HWND handle)
    HDC device = GetDC(handle);
    HDC backBufferDevice = CreateCompatibleDC(device);
    RECT boundRect;

    GetClientRect(handle, &boundRect);

    HBITMAP backbufferBmp = CreateCompatibleBitmap(
        backBufferDevice,
        boundRect.right - boundRect.left,
        boundRect.bottom - boundRect.top
    );
    SelectObject(backBufferDevice, backbufferBmp);

    // This is in a separate function void clear(HDC device)
    RECT rect{ 0, 0, 300, 300 };
    GetClientRect(WindowFromDC(backBufferDevice), &rect);

    FillRect(hdc, &rect, br);

    BitBlt(
        device,
        boundRect.left, boundRect.top,
        boundRect.right - boundRect.left, boundRect.bottom - boundRect.top,
        backBufferDevice,
        0, 0,
        SRCCOPY
    );

    DeleteObject(backbufferBmp);
    DeleteDC(backBufferDevice);

    ReleaseDC(handle, device);
}

LRESULT CALLBACK ProcessMessage(
    HWND         handle,
    unsigned int message,
    WPARAM       wParam,
    LPARAM       lParam
) {
    switch (message) {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    case WM_PAINT:
    case WM_MOUSEMOVE:
        paint(handle);
        return 0;
    case WM_ERASEBKGND:
        return 1;
    default:
        return DefWindowProc(handle, message, wParam, lParam);
    }
}

void main() {
    // ... window initialiation

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

但是当我启动应用程序时,会发生以下情况:

损坏的应用程序

应该发生的是应该在 RGB(20, 20, 20) 中清除窗口。似乎它处于黑白模式并且 WindowFromDC() 失败。第二个不足为奇,但为什么设备是黑白的,我应该如何修复它?

(抱歉英语不好)

标签: c++winapi

解决方案


因此,在进一步研究了这个问题之后,似乎我做错了后缓冲 HBITMAP。它应该被创建为与主 HDC 兼容:

...
HDC device = GetDC(handle);
HDC backBufferDevice = CreateCompatibleDC(device);
RECT boundRect;

GetClientRect(handle, &boundRect);

HBITMAP backbufferBmp = CreateCompatibleBitmap(
    device, // previously was backBufferDevice
    boundRect.right - boundRect.left,
    boundRect.bottom - boundRect.top
);
...

似乎无论如何,第二个 HDC 始终是单色的,尽管它应该与第一个 HDC 兼容,如此处所述。此外,HDC 的维度检索不起作用,因为 HDC 的源不是来自窗口。似乎应该通过以下方式检索它们:

// hdc definition

...
int width = GetDeviceCaps(hdc, HORZRES);
int height = GetDeviceCaps(hdc, VERTRES);
...

很抱歉问了一个问题,而不是看得更远一点,也没有浪费别人的时间。


推荐阅读