0

I read code in MFC, but was confused with the code below:

void EditView::ResetDefaultFont()
{
    HFONT hFont = (HFONT)::GetStockObject(DEFAULT_GUI_FONT);
    CDC* pDC = GetDC();

    CFont* pFont = pDC->SelectObject(CFont::FromHandle(hFont));
    pDC->SelectObject(pFont);
    ::DeleteObject(hFont);

}

Why CDC Select the default font first(CFont* pFont = pDC->SelectObject(CFont::FromHandle(hFont));), but select pFont again?

Al2O3
  • 3,103
  • 4
  • 26
  • 52

2 Answers2

1

The first SelectObject call changes the font selected in the device context.

The second SelectObject call resets the font to whatever it was before the first call.

While that answers the "why" for the second call, which is what you ask about, I do not have any idea what the point of doing the complete call sequence is. I find no documentation results for ResetDefaultFont, neither online in MSDN Library nor in the local Visual Studio 2012 help. Just to be thorough I created a new default MFC project in VS 2012, and used the identifier ResetDefaultFont in the constructor of a class derived from CEditView. It did not compile: no such.

So,

where did you get that ResetDefaultFont function from?

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • This is correct. In old school Win API programming, there was the notion of a 'sandwich' when changing global system objects that were shared resources A font handle to a specific font is obtained, then when you set the font to that new handle, the previous font object is returned so that you can put it back when you are done. Before Win NT these resources were system objects and there were a limited number of GDI handles. It is the responsibility of the programmer to put them back. This was a frequent source of issues in the early Windows world. The early Petzold books are a good resource. – Jeff D. Dec 24 '12 at 07:54
  • @Cheers and hth. - Alf It is in BCGPVisualStudioGUIDemo project from BCG Control. – Al2O3 Dec 24 '12 at 09:12
  • @Ruby Fairly off-topic, but still: The sample code is of really low quality. Apart from the fact that setting a device context's font and immediately undoing that change serves no obvious purpose, the author also felt it was a good idea to delete a **system-controlled** object (the `hFont` returned from `GetStockObject`). You should probably not question the rationale behind this code too much. – IInspectable Dec 26 '12 at 15:47
-2

The answer is quite simple. This code is just for getting the current font of the DC. If they had placed the code following these statements, it would have been obvious.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Geust
  • 1