COleFont 是 MFC 封裝 OLE 字體介面 (IFontDisp) 的包裝類別,提供字體名稱、大小、粗體、斜體、底線、刪除線、字重、字元集等屬性的存取。本文整理其完整成員函數實作,供開發者參考或移植至非 MFC 專案。
// font.h 主要介面宣告
class COleFont : public COleDispatchDriver
{
public:
// 字體名稱
CString GetName();
void SetName(LPCTSTR propVal);
// 字體大小 (CY 型別,單位:1/10000 點)
CY GetSize();
void SetSize(const CY& propVal);
// 粗體
BOOL GetBold();
void SetBold(BOOL propVal);
// 斜體
BOOL GetItalic();
void SetItalic(BOOL propVal);
// 底線
BOOL GetUnderline();
void SetUnderline(BOOL propVal);
// 刪除線
BOOL GetStrikethrough();
void SetStrikethrough(BOOL propVal);
// 字重 (100~1000)
short GetWeight();
void SetWeight(short propVal);
// 字元集
short GetCharset();
void SetCharset(short propVal);
};
#include "stdafx.h"
#include "font.h"
// DISPID 對照表:
// 0x0 Name
// 0x2 Size
// 0x3 Bold
// 0x4 Italic
// 0x5 Underline
// 0x6 Strikethrough
// 0x7 Weight
// 0x8 Charset
CString COleFont::GetName()
{
CString result;
GetProperty(0x0, VT_BSTR, (void*)&result);
return result;
}
void COleFont::SetName(LPCTSTR propVal)
{
SetProperty(0x0, VT_BSTR, propVal);
}
CY COleFont::GetSize()
{
CY result;
GetProperty(0x2, VT_CY, (void*)&result);
return result;
}
void COleFont::SetSize(const CY& propVal)
{
SetProperty(0x2, VT_CY, &propVal);
}
BOOL COleFont::GetBold()
{
BOOL result;
GetProperty(0x3, VT_BOOL, (void*)&result);
return result;
}
void COleFont::SetBold(BOOL propVal)
{
SetProperty(0x3, VT_BOOL, propVal);
}
BOOL COleFont::GetItalic()
{
BOOL result;
GetProperty(0x4, VT_BOOL, (void*)&result);
return result;
}
void COleFont::SetItalic(BOOL propVal)
{
SetProperty(0x4, VT_BOOL, propVal);
}
BOOL COleFont::GetUnderline()
{
BOOL result;
GetProperty(0x5, VT_BOOL, (void*)&result);
return result;
}
void COleFont::SetUnderline(BOOL propVal)
{
SetProperty(0x5, VT_BOOL, propVal);
}
BOOL COleFont::GetStrikethrough()
{
BOOL result;
GetProperty(0x6, VT_BOOL, (void*)&result);
return result;
}
void COleFont::SetStrikethrough(BOOL propVal)
{
SetProperty(0x6, VT_BOOL, propVal);
}
short COleFont::GetWeight()
{
short result;
GetProperty(0x7, VT_I2, (void*)&result);
return result;
}
void COleFont::SetWeight(short propVal)
{
SetProperty(0x7, VT_I2, propVal);
}
short COleFont::GetCharset()
{
short result;
GetProperty(0x8, VT_I2, (void*)&result);
return result;
}
void COleFont::SetCharset(short propVal)
{
SetProperty(0x8, VT_I2, propVal);
}
COleFont font;
font.AttachDispatch(pFontDisp, TRUE); // pFontDisp 為 IFontDisp 指標
// 讀取屬性
CString name = font.GetName();
CY size = font.GetSize();
BOOL bold = font.GetBold();
// 設定屬性
font.SetName(_T("微軟正黑體"));
CY newSize = 120000; // 12 點 = 120000 (1/10000 點)
font.SetSize(newSize);
font.SetBold(TRUE);
font.SetItalic(FALSE);
font.SetWeight(700); // 粗體
font.SetCharset(136); // CHINESEBIG5_CHARSET
CY 型別為 64 位元整數,單位是 1/10,000 點,設定 12 點需傳 120,000。Weight 範圍 100~1000,常用值:400(正常)、700(粗體)。Charset 對應 Windows 字元集常數,如 ANSI_CHARSET(0)、DEFAULT_CHARSET(1)、CHINESEBIG5_CHARSET(136)。GetProperty/SetProperty 呼叫若失敗會拋出 COleException,建議包裝 try-catch。