How to Display Fonts in MFC
The Microsoft Foundation Class (MFC) Library lets a programmer plan the font display of an application through the CFont class. CFont encapsulates all font manipulation techniques, and the class provides four member functions for creating fonts. The following steps demonstrate by example each function and the input parameters it accepts.
- Difficulty:
- Moderately Easy
Instructions
Things You'll Need
- Microsoft Visual Studio
- Book on MFC, such as "Programming Windows With MFC" by Jeff Prosise
-
-
1
Demonstrate all CFont functions (CreateFont, CreateFontIndirect, CreatePointFont and CreatePointFontIndirect) in the same context. You can use Steps 2 to 5 to create an MFC CFont object, give the object parameters through the member function in question, apply the object to a device context and delete the object.
-
2
Display the use of the "CreateFont" function:
//define an MFC device context
CClientDC DC(this);
//create a CFont object
CFont font;
//assign parameters
font.CreateFont(11, 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* pFont = DC.SelectObject(&font);
DC.TextOut(5, 5, "Hello World", 10);
//apply settings of CFont object to device context
DC.SelectObject(pFont);
//delete object
font.DeleteObject();
-
3
Demonstrate the usage of CreateFontIndirect():
//define a device context
CClientDC dc(this);
//create a CFont object
CFont font;
LOGFONT logFont;
logFont.lfHeight = 11;
strcpy(logFont.lfFaceName, "Arial");
//assign parameters
font.CreateFontIndirect(&logFont);
CFont* pFont = dc.SelectObject(&font);
dc.TextOut(5, 5, "Hello World", 10);
//apply settings of CFont object to device context
dc.SelectObject(pFont);
//delete object
font.DeleteObject();
-
4
Illustrate the "CreatePointFont" function:
//define an MFC device context
CClientDC dc(this);
//create a CFont object
CFont font;
font.CreatePointFont(120,"Times New Roman");
//assign parameters
CFont* pFont = dc.SelectObject(&font);
dc.TextOut(5, 5, "Hello World", 10);
//apply settings of CFont object to device context
dc.SelectObject(pFont);
//delete object
font.DeleteObject();
-
5
Give an example to display the "CreatePointFontIndirect" function:
//define a device context
CClientDC dc(this);
//create a CFont object
CFont font;
LOGFONT logFont;
logFont.lfHeight = 140;
strcpy(logFont.lfFaceName, "New Times Roman");
//assign parameters
font.CreatePointFontIndirect(&logFont);
//apply settings of CFont object to device context
CFont* pFont = dc.SelectObject(&font);
dc.TextOut(5, 5, "Hello World", 10);
dc.SelectObject(pFont);
font.DeleteObject()
-
1
Tips & Warnings
There is more to the CFont class than the scope of this article can cover. For full coverage, consult the MSDN Library.