来自位的HBITMAP

时间:2013-01-27 15:56:29

标签: c++ windows winapi

在大捷径中我正在尝试编写程序,该程序通过另一个应用程序的NamedPipe位图从接收到的位图。

我正在单独发送BITMAPINFO结构和位图位,这是我从GetBitmapBits函数获得的。在接收端,我有一个线程,使用HeapAlloc两个全局指针覆盖:pbmi_paint(指向BITMAPINFO)和lpBitmapBits_paint(用于位图位)。 pbmi_paint中的数据似乎总是合法的。然后我尝试在WndProc中使用此代码绘制它:

case WM_PAINT:
    hdc = BeginPaint(hWnd, &ps);
    if(pbmi_paint != NULL && lpBitmapBits_paint != NULL) {
        hBitmap = CreateDIBitmap( hdc,&(pbmi_paint->bmiHeader), CBM_INIT,(LPVOID) lpBitmapBits_paint,pbmi_paint,DIB_RGB_COLORS);
        GetObject(hBitmap, sizeof(bitmap), &bitmap);

        hdcMem = CreateCompatibleDC(hdc);
        oldBitmap = (HBITMAP)SelectObject(hdcMem, hBitmap);
        BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);

        SelectObject(hdcMem, oldBitmap);
        DeleteDC(hdcMem);
        DeleteObject(hBitmap);
    }       
    EndPaint(hWnd, &ps);

然后我什么都没得到(黑色矩形)。我检查了bitmap.bmBits,它等于0x00000000(NULL,位图结构的另一个成员正确设置)。 我还尝试以这种方式手动设置bitmap.bmBits:

case WM_PAINT:
 hdc = BeginPaint(hWnd, &ps);
    if(pbmi_paint != NULL && lpBitmapBits_paint != NULL) {
        hBitmap = CreateDIBitmap( hdc,&(pbmi_paint->bmiHeader), CBM_INIT,(LPVOID) lpBitmapBits_paint,pbmi_paint,DIB_RGB_COLORS);
        GetObject(hBitmap, sizeof(bitmap), &bitmap);
        bitmap.bmBits = lpBitmapBits_paint;
        hBitmap1 =  CreateBitmapIndirect(&bitmap);
        hdcMem = CreateCompatibleDC(hdc);
        oldBitmap = (HBITMAP)SelectObject(hdcMem, hBitmap1);
        BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);

        SelectObject(hdcMem, oldBitmap);
        DeleteDC(hdcMem);
        DeleteObject(hBitmap);
        DeleteObject(hBitmap1);
    }

此后hBitmap1为NULL。所以我的问题是为什么我不能在CreateDIBitmap或CreateBitmapIndirect中使用指向数据的指针?这些功能是否检查数据是否有效?

1 个答案:

答案 0 :(得分:3)

Windows中的位图很乱,尤其是DDB(设备相关位图)。如果可能,我总是喜欢使用DIB(设备无关位图)。它们更容易使用,并且在现代硬件中没有任何明显的性能差异。

使用函数CreateDIBSection()创建DIB,并且像素数据独立完成。像这样:

void *pixels;
HBITMAP hBmp = CreateDIBSection(NULL, pbmi_paint, DIB_RGB_COLORS, &pixels, NULL, 0);
memcpy(pixels, lpBitmapBits_paint, NumBytesInBitmapBits_paint);