MFC改變static text顏色和內容及字體大小
第一種方式:
1. 打開資源視圖。
2. 雙擊打開STATIC所在的對話框。
3. 修改STATIC的ID屬性,這里假設為IDC_STATICMessage。
4.為對話框添加類,假設為CxxxDialog.
5. 選擇對話框,在屬性面板上點擊消息,並選擇WM_CTLCOLOR。
6.在對話框對應類的CPP中會新增下面的代碼:
HBRUSH CxxxDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); //添加自己的代碼 return hbr; }
7. 在上面的代碼中添加修改IDC_TEXT文本顏色的代碼,如下:
HBRUSH CxxxDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (pWnd->GetDlgCtrlID() == IDC_STATICMessage) { pDC->SetTextColor(RGB(0, 0, 250)); } return hbr; }
同樣的方法可應用於修改字體。
動態改變字體內容,使用
GetDlgItem(IDC_STATICMessage)->SetWindowText("I LOVE YOU");
第二種方式:
在實際的應用中,可以用WM_CTLCOLOR 消息改變mfc中控件的顏色,比如現在就來改變一個static text控件的
字體、字體大小、字體顏色和背景色。
例如對話框的類為CTestDlg.
1. 在對話框的類中添加兩個變量.
方法:在classview選項卡中,選擇CTestDlg,右鍵,add member variable.
CBrush m_brush;
CFont m_font;
在OnInitDialog()函數中添加:
m_font.CreatePointFont(150,"華文行楷");//代表15號字體,華文行楷 m_brush.CreateSolidBrush(RGB(0,255,0));//畫刷為綠色
2 添加WM_CTLCOLOR 消息響應,添加的方法為:
add windows message handler->WM_CTLCOLOR->add and edit
3 在HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 函數中的todo后添加代碼,即:
HBRUSH CxxxDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); // TODO: Change any attributes of the DC here if (pWnd->GetDlgCtrlID() == IDC_STATICText) { pDC->SetBkColor(RGB(0,255,0));//背景色為綠色 pDC->SetTextColor(RGB(255, 0, 0));//文字為紅色 pDC->SelectObject(&m_font);//文字為15號字體,華文行楷 return m_brush; } // TODO: Return a different brush if the default is not desired return hbr; }
這樣就可以改變static text的背景色、字體、字體大小和字體顏色了。