C++ 为什么在使用Win32 GDI绘图时需要将句柄保存到旧位图?
以下是WndProc函数中开关的代码,我已经给出了一个示例:C++ 为什么在使用Win32 GDI绘图时需要将句柄保存到旧位图?,c++,winapi,bitmap,gdi,handle,C++,Winapi,Bitmap,Gdi,Handle,以下是WndProc函数中开关的代码,我已经给出了一个示例: 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
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()的返回值
为什么需要在oldBM中保存和恢复SelectObject()的返回值
BeginPaint()
为您提供一个HDC
,其中已经选择了一个默认的HBITMAP
。然后,您将用自己的HBITMAP
来替换它。您没有分配原始的HBITMAP
并且不拥有它,BeginPaint()
分配了它。使用HDC
后,必须恢复原始HBITMAP
,以便EndPaint()
可以在销毁HDC
时释放它,否则它将被泄漏。比泄漏位图资源更糟糕的是双重删除:如果您按照规则玩,并处理掉位图资源(仍在设备上下文中选择),当WM_PAINT
处理程序返回时,系统将执行相同的操作。