WTL 窗口字体类






4.11/5 (6投票s)
2002 年 11 月 7 日
1分钟阅读

168844

1411
使用此类为您的 WTL 应用程序添加额外的字体。
引言
使用这个类可以轻松地向你的 WTL 窗口/对话框添加额外的字体。该类 CWindowFont
将基于现有窗口使用的字体创建一个新的字体。你只需要提供必要的字体属性(粗体、斜体等),非常适合用于基于对话框的应用程序,例如,你想使用粗体字体显示静态控件。
如何使用
要在 WTL 对话框应用程序中使用这个类,只需执行以下操作:
首先包含头文件
#include "windowfont.h"
接下来,为每个要创建的字体添加一个合适的 CWindowFont
成员,例如:
... CWindowFont m_fontBold;
接下来,在你的对话框的 OnInitDialog
函数中,创建字体并将其应用于对话框控件
// Create the font and apply to the IDC_TEXT control
m_fontBold.Apply(m_hWnd, CWindowFont::typeBold, IDC_TEXT);
或者,调用 Create
函数并“手动”应用字体
// Create a bold font if (m_fontBold.Create(m_hWnd, CWindowFont::typeBold)) GetDlgItem(IDC_TEXT).SetFont(m_fontBold);
就是这样了!很简单。例如,我在我拥有的每个“关于”框中使用这个类(为了显示程序版本信息等,以粗体显示)。我还使用这个类创建双高度字体,用于向导的第一页等。
注释
以下字体样式可用(请注意,你可以以任何组合对这些进行 OR 运算):
粗体
(CWindowFont::typeBold
)斜体
(CWindowFont::typeItalic
)下划线
(CWindowFont::typeUnderline
)双高度
(CWindowFont::typeDoubleHeight
)
另外请注意,演示中使用的对话框都设置为使用“MS Shell Dlg”字体 - 如果你想创建双高度字体,这将是最好的选择(因为它比默认的“MS Sans Serif”字体渲染效果更好)。
CWindowFont 源代码
CWindowFont
类足够小,可以发布在这里
#pragma once #include// Wrapper for the Win32 LOGFONT structure class CLogFont : public LOGFONT { public: CLogFont() { memset(this, 0, sizeof(LOGFONT)); } }; // Class used to create a font based on the font used by a specific window class CWindowFont : public CFont { public: // Font styles typedef enum tagEType { typeNormal = 0x00, typeBold = 0x01, typeItalic = 0x02, typeUnderline = 0x04, typeDoubleHeight = 0x08, } EType; public: CWindowFont() : CFont() { } /// hWnd - The window to use for the base font /// nType - Font style flags CWindowFont(HWND hWnd, int nType) { // We need a HWND ATLASSERT(hWnd != NULL); // Create the font Create(hWnd, nType); } virtual ~CWindowFont() { } public: // Create the font // hWnd - The window to use for the base font // nType - Font style flags // return true on success bool Create(HWND hWnd, int nType) { // Be defensive ATLASSERT(hWnd != NULL); ATLASSERT(::IsWindow(hWnd) != FALSE); // Get the font the window is currently using HFONT hFont = (HFONT)::SendMessage(hWnd, WM_GETFONT, 0, 0); // Do we have a font? if (hFont == NULL) return false; CLogFont lf; // Fill the LOGFONT if (::GetObject(hFont, sizeof(lf), &lf) == 0) return false; // Amend the LOGFONT members 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; // Create the new font return CreateFontIndirect(&lf) ? true : false; } // Create the font and apply to a nominate dialog control bool Apply(HWND hWnd, int nType, UINT nControlID) { // First create the font if (!Create(hWnd, nType)) return false; // Apply to the nominated control CWindow wndControl = ::GetDlgItem(hWnd, nControlID); ATLASSERT(wndControl != NULL); // Apply wndControl.SetFont(m_hFont); return true; } };