为什么CreateDIBSection()失败了某些BITMAPINFO?

时间:2011-01-18 09:54:29

标签: c++ windows-xp bitmap createdibsection

我正在尝试使用CreateDIBSection

问题:

在Windows XP中,我尝试拨打CreateDIBSection,它会返回NULLGetLastError = 0

当我尝试更改屏幕分辨率时,例如更改为2048 x 1536,它会返回正确的值。

我测试过这个函数与nMemSize有一些关系(不一定是小数字)。

问题:

是否有任何保证方法可以确保CreateDIBSection返回正确的值?

nScreenWidth = 1024;
nScreenHeight= 768;
 = nScreenWidth*nScreenHeight*3*7
HDC hdc = ::GetDC(hWnd);
m_hBmpMapFile = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, nMemSize, NULL);

BITMAPINFO bmpInfo = {0};
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biWidth = nScreenWidth;
bmpInfo.bmiHeader.biHeight = nScreenHeight;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biBitCount = 24;
bmpInfo.bmiHeader.biCompression = 0;
bmpInfo.bmiHeader.biSizeImage = nMemSize;
bmpInfo.bmiHeader.biXPelsPerMeter = 0;
bmpInfo.bmiHeader.biYPelsPerMeter = 0;
bmpInfo.bmiHeader.biClrUsed = 0;
bmpInfo.bmiHeader.biClrImportant = 0;
bmpInfo.bmiColors[0].rgbBlue = 204;
bmpInfo.bmiColors[0].rgbGreen = 204;
bmpInfo.bmiColors[0].rgbRed = 204;
bmpInfo.bmiColors[0].rgbReserved = 0;
PVOID pvBits;

m_hBmpAllWstDskWallpaper = ::CreateDIBSection(hdc, &bmpInfo, DIB_RGB_COLORS, &pvBits, m_hBmpMapFile, 0); 

1 个答案:

答案 0 :(得分:0)

我怀疑问题可能包含在您未包含的代码部分中(在elipses中)。所以我建议:

  • 检查您的设备上下文是否有效
  • ZeroMemory
  • 添加结构尺寸
  • 和位图尺寸
  • 移动GetLastError调用以确保设备上下文有效(可能是早期的API调用失败)

在我添加上述建议之后,以下代码似乎有效,我希望它有所帮助:

        HDC hdc = ::GetDC(hWnd); 
        int nScreenWidth = 1024; 
        int nScreenHeight= 768; 
        int nMemSize = nScreenWidth*nScreenHeight*3*7;
        HANDLE m_hBmpMapFile = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, nMemSize, NULL); 
        BITMAPINFO bmpInfo; 
        //clear the memory
        ZeroMemory(&bmpInfo.bmiHeader, sizeof(BITMAPINFOHEADER));
        //struct size
        bmpInfo.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
        //dimensions
        bmpInfo.bmiHeader.biWidth = nScreenWidth;
        bmpInfo.bmiHeader.biHeight = nScreenHeight;
        bmpInfo.bmiHeader.biPlanes = 1; 
        bmpInfo.bmiHeader.biBitCount = 32; 
        bmpInfo.bmiHeader.biSizeImage=nMemSize; 
        void *pvBits = NULL;
        HANDLE m_hBmpAllWstDskWallpaper = ::CreateDIBSection(hdc, &bmpInfo, DIB_RGB_COLORS, &pvBits, m_hBmpMapFile, 0);
        int nError = ::GetLastError();