关于GetDIBits和设备上下文的奇怪错误

时间:2017-06-19 11:02:32

标签: c++ mfc hdc getdibits

我今天遇到的一个非常奇怪的问题。使用MFC项目在VC6上运行以下代码,它是黑屏,如果我取出评论,它可以完美地显示桌面图片。但是这些代码是在无限循环中执行的,所以我尝试减少内存复制和内存消耗,如@using (Html.BeginForm("Room", "Booking", FormMethod.Post)) { <table> <tr> <td align="left"><lable for="eventName">Description:</lable></td> <td><input name="eventName" id="eventName"></td> </tr> <tr> <td align="left"><lable for="startDate">Start Date : </td> <td align="left"><label id="startDate" name="startDate" /></td> </tr> <tr> <td></td> </tr> <tr> <td align="right" colspan="2"> <button type="submit" class="btn-primary" name="submit" id="submit">Save</button> </td> </tr> <tr> </tr> </table> } [HttpPost] public ActionResult Room(FormCollection form) { using (BookingEntities ent = new BookingEntities ()) { ReservationTBL Tbl = new ReservationTBL(); Tbl.Description = form["eventName"].ToString(); Tbl.startDate= form["startDate"].ToString(); ent.BookingTBL.Add(Tbl); ent.SaveChanges(); } return View(); } 等。我不明白我的程序与这些注释代码有什么关系。任何人都知道导致问题的原因是什么?为什么?

BitBlt

1 个答案:

答案 0 :(得分:0)

这就是为什么评论该部分不起作用...

HBITMAP hBitmap = CreateCompatibleBitmap(hdcDesktop, desktopWidth, desktopHeight);

HDC hdcMemory = CreateCompatibleDC(hdcDesktop);
SelectObject(hdcMemory, hBitmap);

// BitBlt makes a copy of the desktop here.
BitBlt(hdcMemory, 0, 0, desktopWidth, desktopHeight, hdcDesktop, 0, 0, SRCCOPY);

BITMAPINFO bitmapInfo = {0};
bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);

// the following lines make use of the contents of bitmap in hBitmap
// commenting out the BitBlt would mean the bitmap is uninitialized.
//
GetDIBits(hdcDesktop, hBitmap, 0, 0, NULL, &bitmapInfo, DIB_RGB_COLORS);
BYTE *pData = new BYTE[bitmapInfo.bmiHeader.biSizeImage];
memset(pData, 0, bitmapInfo.bmiHeader.biSizeImage);  // <-- this is unnecessary.

GetDIBits(hdcDesktop, hBitmap, 0, bitmapInfo.bmiHeader.biHeight, pData, &bitmapInfo, DIB_RGB_COLORS);

您可以通过在应用程序的全局范围内创建DIBSection及其关联的BITMAPINFO和pData缓冲区来优化代码。它的尺寸在很长一段时间内都有效......你必须通过处理WM_DISPLAYCHANGE消息(https://msdn.microsoft.com/en-us/library/windows/desktop/dd145210(v=vs.85).aspx)来注意屏幕分辨率的变化。

这样可以避免重复调用CreateCompatibleBitmap()。

但是,我没有找到使用BitBlt()和GetDIBits()来获取桌面位的解决方法。