SelectObject on memory DC

In my program I have a memory DC to which I frequenty draw, then in response to WM_PAINT I quickly BitBlt it to the screen. I've always done the drawing like this, the memory DC is created in response to WM_CREATE btw.

void Draw()
{
    HFONT hPrevFont = (HFONT)SelectObject(m_hMemDC, m_hFont);
    // draw text
    SelectObject(m_hMemDC, hPrevFont);
}

Which should be correct, I've also found out now that I can use SaveDC and RestoreDC for that (especially useful when having a lot of GDI objects)

void Draw()
{
    int nSavedDC = SaveDC(m_hMemDC);
    SelectObject(m_hMemDC, m_hFont);
    // draw text
    RestoreDC(m_hMemDC, nSavedDC);
}

Now I wonder whether it is ok to just save the state of the DC after I created it, and restore it when I'm deleting it. Like this:

int OnCreate(...)
{
    m_hMemDC = CreateMemDC();
    m_nSavedDC = SaveDC(m_hMemDC);
}

void Draw()
{
    SelectObject(m_hMemDC, m_hFont);
    // draw text
}

void OnDestroy()
{
    RestoreDC(m_hMemDC, m_nSavedDC);
    DeleteMemDC(m_hMemDC);
}

This should be alright I think, It's not like anyone else is using my memory DC in the mean time. What do you think?

Heck, is it even necessary to save and restore the DC at all in this case?

EDIT: Yes, I do realize I should delete the memory DC first before deleting the font (because otherwise it would still be used by the memory DC).

Answers


The danger is that you might leave an object selected into your memory DC that can be used by only one DC at a time. Traditionally, you deselect the object out of the DC at the end of your Draw cycle so that the object is available to be selected into another DC. If you delay the deselect, then nobody else can use the object since it's still in your DC.


I see no problem with this. As far as restoring your DC, I think memory leaks could be created by incorrect reference counts if you do not restore the default objects. This is just a guess based on the Microsoft documentation.


Need Your Help

htaccess redirect dynamic url to static url

php apache .htaccess redirect

I've some url rewrites something like that:

Optimising a haversine formula SQL call in PHP

php sql mysql math

I'm creating an MySQL call using PHP, I'm calculating distance using the haversine forumula: