A cool trick to give the Vista UI Font to all your MFC CDialogs

Windows Vista has a new standard user interface font, Segoe UI 9 point, which is not given to you by the operating system when creating a dialog with MS Shell Dlg. Ideally you would like to have your MFC dialogs look modern when running on Windows Vista. That means changing all your fonts to Segoe UI 9 point and/or having separate resources for Vista if you want to work well on all platforms. Instead, there's a cool trick you can use to avoid all that hassle.

The great thing about this solution is that you need not create a new CDialog derived class. In fact the only code changes necessary are those in your application's InitInstance function.

1) In the same file as your application's InitInstance function (just above InitInstance) insert the following code:

#include <afxpriv.h>
#if _MSC_VER < 1300
#include <..\src\occimpl.h>
#else
#include "afxocc.h"
#endif

class CFontOccManager : public COccManager
{
public:
CFontOccManager() { }

virtual const DLGTEMPLATE* PreCreateDialog(_AFX_OCC_DIALOG_INFO* pOccDialogInfo,
const DLGTEMPLATE* pOrigTemplate);
};


void GetDisplayFont(LOGFONT &lf, WORD & wDefSize)
{
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(NONCLIENTMETRICS);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0);
lf = ncm.lfMessageFont;

HDC hDC = ::GetDC(NULL);
if (lf.lfHeight < 0)
lf.lfHeight = -lf.lfHeight;
wDefSize = (WORD)MulDiv(lf.lfHeight, 72, GetDeviceCaps(hDC, LOGPIXELSY));
::ReleaseDC(NULL, hDC);
}

const DLGTEMPLATE* CFontOccManager::PreCreateDialog(_AFX_OCC_DIALOG_INFO* pOccDialogInfo,
const DLGTEMPLATE* pOrigTemplate)
{
const DLGTEMPLATE *lpNewTemplate = COccManager::PreCreateDialog (pOccDialogInfo, pOrigTemplate);

if ((BYTE)GetVersion() >= 6 && !pOccDialogInfo->m_pNewTemplate) {

CDialogTemplate temp(lpNewTemplate);
LOGFONT lf;
WORD wDefSize = 0;
GetDisplayFont( lf, wDefSize );
temp.SetFont(lf.lfFaceName, wDefSize);

pOccDialogInfo->m_pNewTemplate = (DLGTEMPLATE*) temp.Detach();
return pOccDialogInfo->m_pNewTemplate;
}
else
return lpNewTemplate;
}

2) In your InitInstance() function, change:

AfxEnableControlContainer();

to:

AfxEnableControlContainer(new CFontOccManager());

(If you don't have a call to AfxEnableControlContainer already, just add it as above)

That's it. Now your all your dialogs will use Segoe UI 9 point font when running under Windows Vista, and will continue to use your existing font under other platforms.

CPropertySheets/CPropertyPages are a bit more work, however I'll leave that for another day (I posted some hints in the Vista UI Development forum)

[3719 byte] By [Ted.] at [2007-12-24]