这个工程的代码在这里呢。http://download.csdn.net/detail/jiangcaiyang123/3936311
一次编程中想更改对话框的字体,于是想想WTL可不可以做到呢?我当时尝试着使用标准的win32函数CreateFont来创建字体,并且返回字体的句柄。再在CStatic类里面调用SetFont()这个函数来使用字体。但是我没有成功。此外我还使用了LOGFONT结构体和CFont、CLogFont类,但是收效甚微。
// DialogItemFont.h 对话框项的字体 #ifndef _DIALOGITEMFONT_H_ #define _DIALOGITEMFONT_H_ #pragma warning( disable: 4996 ) class CDialogItemFont: public CFont// 对话框项的字体类 { public: CDialogItemFont( void ): CFont( ) // 默认构造函数 { m_bCreateComplete = false; } CDialogItemFont( HFONT hFont ): CFont( hFont ) // 自定义构造函数 { m_bCreateComplete = false; } virtual ~CDialogItemFont( void ) // 将析构函数声明为虚的,子类可以自定义虚构函数 { } bool Create( HWND hWnd, LPLOGFONT pFont ) // 创建字体 { // 1、判断此句柄是否有效且是否是窗体 ATLASSERT( hWnd != NULL ); ATLASSERT( ::IsWindow( hWnd ) != FALSE ); // 2、获取窗口正在使用的字体句柄 HFONT hFont = (HFONT)::SendMessage( hWnd, WM_GETFONT, 0, 0 ); // 3、得到了字体的句柄吗? if ( hFont == NULL ) { hFont = (HFONT)::GetStockObject( SYSTEM_FONT );// 使用系统字体 } LOGFONT lf;// 临时的字体结构体 // 4、填充它 if ( GetObject( hFont, sizeof( lf ), &lf ) == 0 ) return false; // 5、设置想要的字体 if ( pFont != NULL ) { if ( pFont->lfHeight != 0 ) lf.lfHeight = pFont->lfHeight; if ( pFont->lfWidth != 0 ) lf.lfWidth = pFont->lfWidth; if ( pFont->lfEscapement != 0 ) lf.lfEscapement = pFont->lfEscapement; if ( pFont->lfOrientation != 0 ) lf.lfOrientation = pFont->lfOrientation; if ( pFont->lfItalic != 0 ) lf.lfItalic = pFont->lfItalic; if ( pFont->lfUnderline != 0 ) lf.lfUnderline = pFont->lfUnderline; if ( pFont->lfStrikeOut != 0 ) lf.lfStrikeOut = pFont->lfStrikeOut; if ( pFont->lfCharSet != 0 ) lf.lfCharSet = pFont->lfCharSet; if ( pFont->lfOutPrecision != 0 ) lf.lfOutPrecision = pFont->lfOutPrecision; if ( pFont->lfClipPrecision != 0 ) lf.lfClipPrecision = pFont->lfClipPrecision; if ( pFont->lfQuality != 0 ) lf.lfQuality = pFont->lfQuality; if ( pFont->lfPitchAndFamily != 0 ) lf.lfPitchAndFamily = pFont->lfPitchAndFamily; if ( pFont->lfFaceName != 0 ) wcscpy( lf.lfFaceName, pFont->lfFaceName ); } // 6、创建CFont对象 if ( CreateFontIndirect( &lf ) == 0 ) return false; // 7、标记已经成功创建 m_bCreateComplete = true; return true; } bool Apply( HWND hWnd, LPLOGFONT pFont, UINT nID ) // 应用与控件上 { if ( !m_bCreateComplete ) Create( hWnd, pFont ); CWindow wnd = ::GetDlgItem( hWnd, nID ); ATLASSERT( wnd != NULL );// 判断是否传入了正确的ID号和窗体句柄 wnd.SetFont( m_hFont, TRUE );// 设置字体 return true; } private: bool m_bCreateComplete; // 创建已经完成 }; #endif
LRESULT CMainDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { ...(前略) LOGFONT myFont; // 建立自己的字体对象 ZeroMemory( &myFont, sizeof( LOGFONT ) ); // 重要:需将字体的结构清空 myFont.lfHeight = 30; // 填充字体的大小为30磅 wcscpy( myFont.lfFaceName, L"黑体" ); // 字体名称为黑体 m_TitleFont.Apply( this->m_hWnd, &myFont, IDC_PIXEL_AVAILABLE ); // 初始化静态文本 m_PixelAvailable.Attach( this->m_hWnd ); m_PixelAvailable.SetDlgItemText( IDC_PIXEL_AVAILABLE, TEXT( "可用的分辨率" ) ); return TRUE; }