Why do I need to save handle to an old bitmap while drawing with Win32 GDI?

大城市里の小女人 提交于 2021-02-10 11:53:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!