为什么在使用 Win32 GDI 绘图时需要保存旧位图的句柄?
Why do I need to save handle to an old bitmap while drawing with Win32 GDI?
这里是 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()的return值?
why is it necessary to save and restore the return value of SelectObject() in oldBM?
BeginPaint()
给你一个 HDC
,其中已经选择了默认的 HBITMAP
。然后,您将用自己的 HBITMAP
替换它。你没有分配原来的HBITMAP
也不拥有它,BeginPaint()
分配了它。使用完HDC
后必须恢复原来的HBITMAP
,以便EndPaint()
在销毁HDC
时释放它,否则会泄露。
这里是 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()的return值?
why is it necessary to save and restore the return value of SelectObject() in oldBM?
BeginPaint()
给你一个 HDC
,其中已经选择了默认的 HBITMAP
。然后,您将用自己的 HBITMAP
替换它。你没有分配原来的HBITMAP
也不拥有它,BeginPaint()
分配了它。使用完HDC
后必须恢复原来的HBITMAP
,以便EndPaint()
在销毁HDC
时释放它,否则会泄露。