问题描述
以下是我以WndProc函数中的开关代码为例:
Here is the code from switch in WndProc function I've been given as an example:
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()的返回值?
My question is 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
,否则它将被泄漏.
BeginPaint()
gives you an HDC
that already has a default HBITMAP
selected into it. You are then replacing that with your own HBITMAP
. You did not allocate the original HBITMAP
and do not own it, BeginPaint()
allocated it. You must restore the original HBITMAP
when you are done using the HDC
so that EndPaint()
can free it when destroying the HDC
, otherwise it will be leaked.
这篇关于为什么在用Win32 GDI绘图时需要将句柄保存到旧的位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!