0

所以,我对 WinAPI 很陌生,我已经成功加载了一个可以用箭头键移动的精灵。我的老师告诉我要非常小心“内存泄漏”,我不确定如何以正确的方式释放内存,因为 C++ 在我进行控制台编程时已经为我完成了它。我运行了这个程序,它在移动角色一段时间后冻结了我的电脑一分钟,所以我想我做错了什么。你能告诉我如何正确释放内存(如果我做错了)以及我的位图方法是否有任何问题需要优化?谢谢!这是代码。

void LoadAndBlitBitmap(LPCSTR szFileName, HWND hwnd, HDC winDC, int xPos, int yPos)
{
//DEFINITIONS

/*TransparentBlt(destDC, destXpos, destYpos, sizeX, sizeY, srcDC, 0, 0, sizeX, sizeY, RGB(a, b, c)) = TRANSPARENT BITMAP BLIT. Ex. RGB(255, 255, 255) if background is white*/
/*BitBlt(destDC, destXpos, destYpos, sizeX, sizeY, srcDC, 0, 0, SRCCOPY);                           = SOLID BITMAP BLIT WITH NO TRANSPARENCY*/ 

//END DEFINITIONS

//-----Get the size of the window---------
RECT rect;
int win_width   = 0;
int win_height  = 0;
if(GetWindowRect(hwnd, &rect))
{
    win_width   = rect.right - rect.left;   //Subtracting the right coordinate with the left gives the width
    win_height  = rect.bottom - rect.top;   //Subtracting the bottom coordinate with the top gives the height
}
//----------------------------------------

HDC     hdcMem  = CreateCompatibleDC(winDC);                                //Create the DC that will hold the off-screen printing. (Double Buffering "Anti-Flicker" Method)
HBITMAP hbmMem  = CreateCompatibleBitmap(winDC, win_width, win_height);     //Create the bitmap with the size of the window
HANDLE  hOld    = SelectObject(hdcMem, hbmMem);                             //Set the paintable bitmap to the off-screen DC


//Draw to the off-screen DC
HBITMAP bitmap = (HBITMAP)LoadImage(NULL, szFileName, IMAGE_BITMAP, 69, 69, LR_LOADFROMFILE);       //Load the .bmp from a file
HDC blockDC = CreateCompatibleDC(NULL);                                                             //Create a DC to hold the .bmp
SelectObject(blockDC, bitmap);                                                                      //Select the .bmp to the DC
TransparentBlt(hdcMem, xPos, yPos, 69, 69, blockDC, 0, 0, 69, 69, RGB(255, 255, 255));              //Blit the .bmp to the DC*/


//Transfer off-screen DC to the screen
BitBlt(winDC, 0, 0, win_width, win_height, hdcMem, 0, 0, SRCCOPY);

// Uninitialize and deallocate resources
SelectObject(hdcMem, hOld);
DeleteDC(hdcMem);
SelectObject(blockDC, hOld);
DeleteDC(blockDC);
DeleteObject(bitmap);
}
4

1 回答 1

2

有两点不对:

SelectObject(blockDC, hOld);

hOld不是来自blockDC,它来自hdcMem。您甚至没有从blockDC. 改成:

HBITMAP hOld2 = SelectObject(blockDC, bitmap);
// and
SelectObject(blockDC, hOld2);

其次,您不会hbmMem在任何地方删除。在底部,添加:

DeleteObject(hbmMem);

实际上,第三件事也是错误的——你没有检查你所做的任何 API 调用中的失败。您应该检查是否CreateCompatibleDC返回 NULL,如果是,则中止和清理。

于 2013-09-25T23:30:28.107 回答