EvoTalk

05 七月, 2007

MFC: Set Font From File or Resource

Posted by: asd In: Code Snippet| 程式設計 ()

1. set font from file

Assume there is a font file "ladderkk.ttf" under work dir and declare member variable 「CFont m_font」 in class private section。

C++:
  1. if (AddFontResource("ladderkk.ttf") == 0) {
  2. AfxMessageBox("add font fail");
  3. return FALSE;
  4. }
  5. LOGFONT lf;
  6. memset(&lf, 0, sizeof(LOGFONT));   // Clear out structure.
  7. lf.lfHeight = 20;                           // Request a 20-pixel-high font
  8.  
  9. strcpy(lf.lfFaceName, "LadderKK");    //    with face name "Arial".
  10. m_font.CreateFontIndirect(&lf);       // Create the font.
  11.  
  12. GetDlgItem(IDC_EDIT1)->SetFont(&m_font);

2. set font from resource

in your rc file , add

4 FONT "ladderkk.ttf"

in your stdafx.h add

#define _WIN32_WINNT 0x0500
#define WINVER 0x0500

in your cpp file

C++:
  1. HINSTANCE h=AfxGetInstanceHandle();
  2. ULONG nFont = 1;
  3.  
  4. HRSRC hr=FindResource(h, "#4" , RT_FONT);
  5. HGLOBAL hg=LoadResource(h,hr);
  6. LPSTR lp=(LPSTR)LockResource(hg);
  7. DWORD dwSize = SizeofResource(h, hr);
  8.  
  9. HANDLE handle = AddFontMemResourceEx(lp, dwSize, 0, &nFont);
  10.  
  11. // TODO: Add extra initialization here
  12. LOGFONT lf;
  13. memset(&lf, 0, sizeof(LOGFONT));   // Clear out structure.
  14. lf.lfHeight = 20;                  // Request a 20-pixel-high font
  15.  
  16. strcpy(lf.lfFaceName, "LadderKK");    //    with face name "Arial".
  17. m_font.CreateFontIndirect(&lf);    // Create the font.
  18.  
  19. GetDlgItem(IDC_EDIT1)->SetFont(&m_font);

Attension

  1. if no define 「_WIN32_WINNT」and 「WINVER」, vc6 compiler can't find 「AddFontMemResourceEx」
  2. When exiting the app, call 「RemoveFontResource」or 「RemoveFontMemResourceEx」

Reference

使用正確的 MFC 中 SetFont() 函式

Using the Windows Headers
Tags: ,

Releated Posts



No Responses to "MFC: Set Font From File or Resource"

Comment Form