As Richard stated, it is possible. This is an instance where the automatic construction/destruction mechanism of C++ can come in very handy. The late Paul DiLascia used to write about the concept of excursion classes and this is an ideal candidate for one. I use them often and I made one specifically for selecting objects.
Here is a partial listing of it that uses handles and not their MFC counterparts :
class CSelectObject
{
public:
CSelectObject() {}
CSelectObject( HDC hDC, HGDIOBJ hObject, bool autodelete=false )
{
Select( hDC, hObject, autodelete );
}
void Select( HDC hDC, HGDIOBJ hObject, bool autodelete=false )
{
m_hDC = hDC;
m_hOldObject = SelectObject( hDC, hObject );
m_Delete = autodelete;
}
virtual ~CSelectObject()
{
if( m_hDC )
SelectObject( m_hDC, m_hOldObject );
if( m_Delete )
DeleteObject( m_hOldObject );
}
protected:
HGDIOBJ m_hOldObject { nullptr };
HDC m_hDC { nullptr };
bool m_Delete { false };
};
if used for this case the code could look like this :
auto hbmp = CreateCompatibleBitmap( hdc, prc->right, prc->bottom );
CSelectObject selbmp( hdcWorkingBackBuffer, hmp, true );
When the selbmp object falls out of scope the previous handle will be selected back into the context and the bitmap object will be deleted.