Change default dialog font


Sometimes it is desirable to change the default font specified in dialog templates
(usually "MS Sans Serif", 8 pts.) at runtime (dynamically). For example, you may
want to increase the font size to make it more readable under higher screen resolutions.
MFC library contains a class CDialogTemplate, that serves exactly this
purpose, but MS has not bothered to include its description in standard MFC reference.
This is how you can use this class in your code:

1. place the following string somewhere in your "stdafx.h" file:

#include <afxpriv.h>

2. override DoModal() function in your dialog class:

int CSimpleDialog::DoModal()
   CDialogTemplate dlt;
   int             nResult;

   // load dialog template
   if (!dlt.Load(MAKEINTRESOURCE(CSimpleDialog::IDD))) return -1;

   // set your own font, for example "Arial", 10 pts.
   dlt.SetFont("Arial", 10);

   // get pointer to the modified dialog template
   LPSTR pdata = (LPSTR)GlobalLock(dlt.m_hTemplate);

   // let MFC know that you are using your own template
   m_lpszTemplateName = NULL;

   // display dialog box
   nResult = CDialog::DoModal();

   // unlock memory object

   return nResult;

It may be reasonable to choose a font for your dialog box according to user-specified
schemes (those in Control Panel / Display / Appearance). Unfortunately I was unable to
find any simple ways to get font settings for the dialog boxes. A possible alternative is
to use font settings for icon titles and some related controls (like tree and list
controls), that can be retrieved by SystemParametersInfo() function. Here
is a simple procedure that returns the face name and the size in points for this font:

void GetSystemIconFont(CString& strFontName,int& nPointSize)
   LOGFONT lf;

   // get LOGFONT structure for the icon font

   // getting number of pixels per logical inch
   // along the display height
   HDC hDC    = ::GetDC(NULL);
   int nLPixY = GetDeviceCaps(hDC, LOGPIXELSY);

   // copy font parameters
   nPointSize  = -MulDiv(lf.lfHeight,72,nLPixY);
   strFontName = lf.lfFaceName;

Date Last Updated: April 3, 1999

More by Author

Must Read