CFont class encapsulates the functionalities needed to manipulate the Fonts in Windows programming. A font can be created in 4 ways with a CFont class using CreateFont, CreateFontIndirect, CreatePointFont, or CreatePointFontIndirect functions. This CFont Samples page tries to give a piece of sample code for all of the above functions.
CFont Sample for using CFont :: CreateFont:
The following CFont sample illustrates how to create a font using CreateFont function of the CFont class.
CClientDC dc(this); CFont l_font; l_font.CreateFont(14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, 0, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_ROMAN, "Times New Roman"); CFont* l_old_font = dc.SelectObject(&l_font); dc.TextOut(50, 50, "Hello World"); dc.SelectObject(l_old_font); // Delete the font object. l_font.DeleteObject();
In the above CFont Sample, the CreateFont function uses all default parameters (either 0 or Default constants), except for the height parameter. If CreateFont is called as above, the MFC framework will select the best fit parameters by itself and create a font accordingly.
CFont Sample for using CFont :: CreateFontIndirect:
This part of CFont sample illustrates the usage of CreateFontIndirect.
CClientDC dc(this); CFont l_font; LOGFONT lf; lf.lfHeight = 12; strcpy(lf.lfFaceName, "Arial"); // Need a face name "Arial". l_font.CreateFontIndirect(&lf); CFont* l_old_font = dc.SelectObject(&l_font); dc.TextOut(50, 50, "Hello World"); dc.SelectObject(l_old_font); // Delete the font object. l_font.DeleteObject();
The LOGFONT is a structure with all members required for the Font object.
CFont Sample for using CFont :: CreatePointFont:
This part of the sample illustrates the use of CreatePointFont for creating a font.
CClientDC dc(this); CFont l_font; l_font.CreatePointFont(140,"Times New Roman"); CFont* l_old_font = dc.SelectObject(&l_font); dc.TextOut(50, 50, "Hello World"); dc.SelectObject(l_old_font); // Delete the font object. l_font.DeleteObject();
The first parameter of the CreatePointFont function is the height of the Font in tenths of a point. The return value of this function is non-zero value if successful.
CFont Sample for using CFont :: CreatePointFontIndirect:
CClientDC dc(this); CFont l_font; LOGFONT lf; lf.lfHeight = 120; strcpy(lf.lfFaceName, "Arial"); // Need a face name "Arial". l_font.CreatePointFontIndirect(&lf); CFont* l_old_font = dc.SelectObject(&l_font); dc.TextOut(50, 60, "Hello World"); dc.SelectObject(l_old_font); // Delete the font object. l_font.DeleteObject();
Usually it is better to use either CreatePointFont or CreatePointFontIndirect functions as they reduce the head-ache of thinking about the width, weight and such parameters.
Also, in the above CFont sample the l_font is deleted in the end. It is a good programming practice as advised by Windows Programming manuals to delete the Objects after removing them from the current device context.