问题
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;
My question is why is it necessary to save and restore the return value of SelectObject() in oldBM?
回答1:
why is it necessary to save and restore the return value of SelectObject() in oldBM?
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.
来源:https://stackoverflow.com/questions/30451235/why-do-i-need-to-save-handle-to-an-old-bitmap-while-drawing-with-win32-gdi