Introduction
Use this class to easily add additional fonts to your WTL windows/dialogs. The class, CWindowFont
, will create a new font based on the font used by an existing window. All you supply are the necessary font attributes (bold, italic, etc.), perfect for use with a dialog based application where you want to display, for example, a static control using a bold font.
How to use
To use this class in a WTL dialog application, simply do the following:
First include the header file:
#include "windowfont.h"
Next, add a suitable CWindowFont
member for each font you wish to create, e.g.:
...
CWindowFont m_fontBold;
Next, in your dialogs OnInitDialog
function, create the font and apply it to a dialog control:
m_fontBold.Apply(m_hWnd, CWindowFont::typeBold, IDC_TEXT);
Alternatively, call the Create
function and apply the font "by hand":
if (m_fontBold.Create(m_hWnd, CWindowFont::typeBold))
GetDlgItem(IDC_TEXT).SetFont(m_fontBold);
That's it! Simple. For example, I use this class in every "About" box I have (to display the program version info, etc, in bold). I have also used this class to create a double-height font for use on the first page of a wizard, etc.
Notes
The following font styles are available (note that you can OR these together in any combination):
Bold
(CWindowFont::typeBold
)
Italic
(CWindowFont::typeItalic
)
Underline
(CWindowFont::typeUnderline
)
Double-height
(CWindowFont::typeDoubleHeight
)
Note also that the dialogs used in the demo are all set to use the "MS Shell Dlg" font - which is best if you want to create a double-height font (as it will render better than the default "MS Sans Serif" font).
CWindowFont Source
The CWindowFont
class is small enough to post here:
#pragma once
#include
class CLogFont : public LOGFONT
{
public:
CLogFont()
{
memset(this, 0, sizeof(LOGFONT));
}
};
class CWindowFont : public CFont
{
public:
typedef enum tagEType
{
typeNormal = 0x00,
typeBold = 0x01,
typeItalic = 0x02,
typeUnderline = 0x04,
typeDoubleHeight = 0x08,
} EType;
public:
CWindowFont() : CFont()
{
}
CWindowFont(HWND hWnd, int nType)
{
ATLASSERT(hWnd != NULL);
Create(hWnd, nType);
}
virtual ~CWindowFont()
{
}
public:
bool Create(HWND hWnd, int nType)
{
ATLASSERT(hWnd != NULL);
ATLASSERT(::IsWindow(hWnd) != FALSE);
HFONT hFont = (HFONT)::SendMessage(hWnd, WM_GETFONT, 0, 0);
if (hFont == NULL)
return false;
CLogFont lf;
if (::GetObject(hFont, sizeof(lf), &lf) == 0)
return false;
if (nType & typeBold)
lf.lfWeight = FW_BOLD;
if (nType & typeItalic)
lf.lfItalic = TRUE;
if (nType & typeUnderline)
lf.lfUnderline = TRUE;
if (nType & typeDoubleHeight)
lf.lfHeight *= 2;
return CreateFontIndirect(&lf) ? true : false;
}
bool Apply(HWND hWnd, int nType, UINT nControlID)
{
if (!Create(hWnd, nType))
return false;
CWindow wndControl = ::GetDlgItem(hWnd, nControlID);
ATLASSERT(wndControl != NULL);
wndControl.SetFont(m_hFont);
return true;
}
};