How can I reuse a HBITMAP handle?
I have to draw a bitmap multiple times. It's loaded from file. I can reload it every time I have to use it in SelectObject
the following way:
void drawBitmap(HWND hWnd, int xPos, int yPos) {
HBITMAP hBmp = (HBITMAP) LoadImage(NULL, "image.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
HDC hDC = GetDC(hWnd);
HDC hdcMem = CreateCompatibleDC(hDC);
SelectObject(hdcMem, hBmp);
BitBlt(hDC, xPos, yPos, 7, 7, hdcMem, 0, 0, SRCCOPY);
}
drawBitmap(hMainWnd, 0, 0);
drawBitmap(hMainWnd, 14, 0);
drawBitmap(hMainWnd, 28, 0);
But is it also possible to do something like this?
HBITMAP hBmp = (HBITMAP) LoadImage(NULL, "image.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
void drawBitmap(HWND hWnd, int xPos, int yPos) {
HBITMAP hBmp2 = hBmp;
HDC hDC = GetDC(hWnd);
HDC hdcMem = CreateCompatibleDC(hDC);
SelectObject(hdcMem, hBmp2);
BitBlt(hDC, xPos, yPos, 7, 7, hdcMem, 0, 0, SRCCOPY);
}
drawBitmap(hMainWnd, 0, 0);
drawBitmap(hMainWnd, 14, 0);
drawBitmap(hMainWnd, 28, 0);
But this only draws one bitmap...
MSDN says开发者_如何学C:
The
SelectObject
function selects an object into the specified device context (DC). The new object replaces the previous object of the same type.
So maybe my hBmp
is wasted after SelectObject
is called. But I copied it into hBmp2
first, then what's the problem?
You are not deleting the memory DC when you are done with it. That means the DC is leaked, and the bitmap is still selected in that leaked DC. And according to the SelectObject
documentation: "An application cannot select a single bitmap into more than one DC at a time."
So the second SelectObject
fails because the bitmap is still selected in the first HDC
.
Clean up after yourself by calling DeleteDC
at the end of the drawBitmap
function (and also call DeleteObject
on the hBmp when you are done with it).
Additionally, the HBITMAP hBmp2 = hBmp;
line accomplishes nothing. You're just assigning the handle to a different variable. It's still the same handle to the same bitmap.
精彩评论