STM_SETIMAGE或CStatic::SetBitmap(HBITMAP hBitmap)返回的是先前的资源句柄,同时深拷贝一份当前的(参数传入的)资源句柄。
解决:
win32
HBITMAP hOldBmp = (HBITMAP)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);
if( NULL != hOldBmp )
{
//不再使用,如果需要使用,请另作保存等其它处理。
DeleteObject( hOldBmp );
}
mfc:
HBITMAP hOldBitmap = pStatic ->SetBitmap( imgIcon );
if( NULL != hOldBitmap )
{
//如需再用,请保存等其它处理
DeleteObject( hOldBitmap );
}
以win32分析为例
HBITMAP hNewBmp = NULL;
... //初始化hNewBmp
HBITMAP hOldBmp1 = (HBITMAP)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap); //第一次复制
HBITMAP hOldBmp2 = (HBITMAP)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap); //第二次复制,返回第一次复制的hNewBmp
HBITMAP hOldBmp3 = (HBITMAP)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap); //第二次复制,返回第2次复制的hNewBmp
//可以发现
assert( hOldBmp2 != hOldBmp3 ); //此断言成立!
//所以,如果再使用返回的资源句柄,正确的做法:
HBITMAP hOldBmp = (HBITMAP)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);
if( NULL != hOldBmp )
{
//不再使用,如果需要使用,请另作保存等其它处理。
DeleteObject( hOldBmp );
}