在使用Win32 GDI进行绘制时,为什么需要将句柄保存到旧位图?

时间:2015-05-26 06:41:00

标签: c++ winapi bitmap gdi handle

以下是WndProc函数中switch的代码我作为示例给出了:

case WM_PAINT:
 hdc = BeginPaint(hWnd, &ps);
 // Create a system memory device context.
 bmHDC = CreateCompatibleDC(hdc);
// Hook up the bitmap to the bmHDC.
 oldBM = (HBITMAP)SelectObject(bmHDC, ghBitMap);
 // Now copy the pixels from the bitmap bmHDC has selected
 // to the pixels from the client area hdc has selected.
 BitBlt(
 hdc, // Destination DC.
 0, // 'left' coordinate of destination rectangle.
 0, // 'top' coordinate of destination rectangle.
 bmWidth, // 'right' coordinate of destination rectangle.
 bmHeight, // 'bottom' coordinate of destination rectangle.
 bmHDC, // Bitmap source DC.
 0, // 'left' coordinate of source rectangle.
 0, // 'top' coordinate of source rectangle.
 SRCCOPY); // Copy the source pixels directly
 // to the destination pixels
 // Select the originally loaded bitmap.
 SelectObject(bmHDC, oldBM);
 // Delete the system memory device context.
 DeleteDC(bmHDC);
 EndPaint(hWnd, &ps);
 return 0; 

我的问题是为什么有必要在oldBM中保存和恢复SelectObject()的返回值?

1 个答案:

答案 0 :(得分:3)

  

为什么有必要在oldBM中保存和恢复SelectObject()的返回值?

BeginPaint()为您提供已选择默认HDC的{​​{1}}。然后,您将使用自己的HBITMAP替换它。您没有分配原始HBITMAP而没有拥有它,HBITMAP已分配它。您必须在使用BeginPaint()后恢复原始HBITMAP,以便HDC在销毁EndPaint()时可以将其释放,否则会泄露。