www.gusucode.com > VC++枚举Windows可用字体并预览-源码程序 > VC++枚举Windows可用字体并预览-源码程序\code\WizFontExampleStatic.cpp

    // WizFontExampleStatic.cpp : implementation file
// Download by http://www.NewXing.com

#include "stdafx.h"
#include "EnumFonts.h"
#include "WizFontExampleStatic.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CWizFontExampleStatic

CWizFontExampleStatic::CWizFontExampleStatic()
{
}

CWizFontExampleStatic::~CWizFontExampleStatic()
{
}


BEGIN_MESSAGE_MAP(CWizFontExampleStatic, CStatic)
	//{{AFX_MSG_MAP(CWizFontExampleStatic)
	ON_WM_PAINT()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CWizFontExampleStatic message handlers

//初始化字符串要使用的字体
void CWizFontExampleStatic::SetFont (LPCTSTR fontname, int pp_size, BOOL bItal, BOOL bBold, BOOL bUnder)
{
	memset (&m_lf, 0, sizeof(m_lf));
	m_lf.lfCharSet	= DEFAULT_CHARSET;
	strcpy(m_lf.lfFaceName, fontname);
	m_lf.lfHeight = pp_size*10;
	m_lf.lfItalic = bItal;
	m_lf.lfUnderline = bUnder;
	m_lf.lfWeight = (bBold) ? FW_BOLD : FW_REGULAR;

	//获得设备场景
	CClientDC dc (this);
	if (m_Font.GetSafeHandle())
		m_Font.DeleteObject();

	//创建字体
	if (!m_Font.CreatePointFontIndirect(&m_lf, &dc))
	{ 
		ASSERT(0); return;
	}
	

	CString text;
	TCHAR bold_ch = (bBold) ?  'B' : ' ';
	TCHAR ital_ch = (bItal) ?  'I' : ' ';
	TCHAR Under_ch = (bUnder) ?  'U' : ' ';
	text.Format (_T("%s size % d %c %c %c"), fontname, pp_size, bold_ch, ital_ch, Under_ch);
	m_strSample = text;

	//重画该窗体
	CWnd* parent = GetParent();
	if (parent)
	{
		CRect r;
		GetWindowRect(r);
		parent->ScreenToClient(&r);
		parent->InvalidateRect(r);
		parent->UpdateWindow();
	}
	Invalidate(TRUE);
}

//按设定的格式显示字符串
void CWizFontExampleStatic::OnPaint() 
{
	//获得设备场景
	CPaintDC dc(this); 

	CRect rcText;
	CFont *oldFont;
	CSize TextExtent;
	COLORREF crText;
	TEXTMETRIC tm;
	int bkMode, len, x, y;

	//要显示的字符串
	CString strSample = _T("AaBbYyZz ");
	strSample += m_strSample;

	if (!m_Font.GetSafeHandle())
		return;

	//获得客户区大小
	GetClientRect( &rcText );

	//将字体选进设备场景
	oldFont = dc.SelectObject( &m_Font );
	crText = dc.SetTextColor(GetSysColor(COLOR_WINDOWTEXT));
	bkMode = dc.SetBkMode(TRANSPARENT);

	//计算字符串的大小
	dc.GetTextMetrics( &tm );

	len = strSample.GetLength();
	TextExtent = dc.GetTextExtent(strSample, len);
	TextExtent.cy = tm.tmAscent - tm.tmInternalLeading;

	if ((TextExtent.cx >= (rcText.right - rcText.left)) ||
			(TextExtent.cx <= 0))
		x = rcText.left;
	else
		x = rcText.left + ((rcText.right - rcText.left) - TextExtent.cx) / 2;

	y = min(rcText.bottom,
		rcText.bottom - ((rcText.bottom - rcText.top) - TextExtent.cy) / 2);

	//显示字符串
	dc.ExtTextOut(x, y - (tm.tmAscent), ETO_CLIPPED, &rcText,
		strSample, len, NULL);

	dc.SetBkMode(bkMode);
	dc.SetTextColor(crText);

	//还原字体
	if (oldFont)
		dc.SelectObject(oldFont);
}