Exception thrown on CDC::SelectObject

Flaviu_ 911 Reputation points
2021-10-31T17:27:48.83+00:00

I have the following code:

void CMyHeaderCtrl::OnNMCustomdraw(NMHDR* pNMHDR, LRESULT* pResult)  
{  
	LPNMLVCUSTOMDRAW pNMCD = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR);  
	// TODO: Add your control notification handler code here  
  
	*pResult = CDRF_DODEFAULT;  
  
	switch (pNMCD->nmcd.dwDrawStage)  
	{  
	case CDDS_PREPAINT:  
		*pResult = CDRF_NOTIFYITEMDRAW | CDRF_NOTIFYPOSTPAINT;  
		break;  
	case CDDS_ITEMPREPAINT:  
		break;  
	case CDDS_POSTPAINT:  
		CRect rect;  
		GetClientRect(&rect);  
		const int nWidth = rect.right - rect.left;  
		const int nHeight = rect.bottom - rect.top;  
  
		CDC* pDC = CDC::FromHandle(pNMCD->nmcd.hdc);  
		CDC MemDC;  
		MemDC.CreateCompatibleDC(pDC);  
		CBitmap bitmap;  
		bitmap.CreateCompatibleBitmap(pDC, nWidth, nHeight);  
		CBitmap* pOldBitmap = (CBitmap*)MemDC.SelectObject(bitmap);  
		// do nothing  
		MemDC.SelectObject(pOldBitmap);    // <--- error here  
		DeleteObject(bitmap);  
		DeleteDC(MemDC);  
		break;  
	}  
}  

but I encountered an error:

Exception thrown at 0x00007FFF038A5465 (mfc140ud.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0x0000000000850017.  

145291-image.png

Why I got this ? What is wrong here ? BTW, pOldBitmap is not null and valid.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,519 questions
{count} votes