●オーディオプレイヤ開発記 その15
今回は、フォントを管理する CFont クラスを作成します。これによって例えば、ラベルなどに表示される文字のフォントを設定できるようにします。
それでは、早速 CFont クラスを作成します。
//----------------------------------------------------------------------------
// Font.h : フォントの作成・管理・破棄を行う
//----------------------------------------------------------------------------
#ifndef FontH
#define FontH
//----------------------------------------------------------------------------
// フォントの作成・管理・破棄を行うクラス
//----------------------------------------------------------------------------
class CFont
{
public: // 関数
CFont(): m_hFont(0) { }
virtual ~CFont() { Destroy(); }
virtual BOOL Create(int nHeight, int nWidth, int nEscapement,
int nOrientation, int nWeight, BYTE bItalic,
BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet,
BYTE nOutPrecision, BYTE nClipPrecision, BYTE nQuality,
BYTE nPitchAndFamily, LPCTSTR lpszFacename)
{
m_hFont = CreateFont(nHeight, nWidth, nEscapement, nOrientation,
nWeight, bItalic, bUnderline, cStrikeOut,
nCharSet, nOutPrecision, nClipPrecision,
nQuality, nPitchAndFamily, lpszFacename);
return (m_hFont ? TRUE : FALSE);
}
virtual BOOL CreateIndirect(const LOGFONT* pLogFont) {
m_hFont = CreateFontIndirect(pLogFont);
return (m_hFont ? TRUE : FALSE);
}
virtual void Destroy() {
if(m_hFont) DeleteObject(m_hFont), m_hFont = 0;
}
protected: // メンバ変数
HFONT m_hFont;
public: // メンバ変数の取得・設定
operator HFONT() const { return m_hFont; }
};
//----------------------------------------------------------------------------
#endif
これを、コントロールなどに対して適用できるようにするため、CWnd クラスに SetFont 関数を追加します。
virtual void SetFont(HFONT hFont, BOOL fRedraw = TRUE) {
SendMessage(m_hWnd, WM_SETFONT, (WPARAM)hFont, (LPARAM)fRedraw);
}
これで、フォントを設定できるようになりました。
ところでさっき気づいたんですけど、CStatic クラスの SetSizeToTextSize 関数がデフォルトのシステムフォントにしか対応していませんでしたので、これを修正します。ついでに必要となる関数もいくつか追加しておきます。
まず、CWnd::GetFont 関数を追加します。
virtual HFONT GetFont() const {
return (HFONT)SendMessage(m_hWnd, WM_GETFONT, 0, 0);
}
次に、CDC::SelectFont 関数を追加します。
virtual HFONT SelectFont(HFONT hFont) {
return (HFONT)SelectObject(m_hDC, hFont);
}
そして、CStatic::GetTextHeight, GetTextWidth 関数を修正します。
virtual int GetTextHeight() const {
if(!m_hWnd) return -1;
CClientDC dc(m_hWnd);
HFONT hFont = GetFont();
HFONT hOrgFont = 0;
if(hFont)
hOrgFont = dc.SelectFont(hFont);
int height = dc.GetTextHeight(GetText());
if(hOrgFont)
dc.SelectFont(hOrgFont);
return height;
}
virtual int GetTextWidth() const {
if(!m_hWnd) return -1;
CClientDC dc(m_hWnd);
HFONT hFont = GetFont();
HFONT hOrgFont = 0;
if(hFont)
hOrgFont = dc.SelectFont(hFont);
int width = dc.GetTextWidth(GetText());
if(hOrgFont)
dc.SelectFont(hOrgFont);
return width;
}
これで、フォントを変更した場合でも、SetSizeToTextSize 関数がきちんと動作するようになりました。
次は、再生時間表示用ラベルを管理する CTimeLabel_MainWnd クラスを作成する予定です。