MFC改變按鈕的顏色,方法簡單,實用
手動新增訊息對映的方法實現改變按鈕的顏色,不必建立新的類!
1.將button修改為owner draw 型別
2.過載OnDrawItem函式,並對其改寫
在適當的位置新增下面的語句
afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct);
ON_WM_DRAWITEM()
3.在訊息響應函式裡新增如下程式碼:
void CXXX::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);
ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON);
CString strText;
((CButton *)GetDlgItem(nIDCtl))->GetWindowText(strText);
SetBkMode(lpDrawItemStruct->hDC, TRANSPARENT);
//if (lpDrawItemStruct->itemState&ODS_SELECTED)
{
CBrush brush(RGB(255, 0, 0));
dc.FillRect(&(lpDrawItemStruct->rcItem), &brush);
DrawText(lpDrawItemStruct->hDC, strText, strText.GetLength(),
&lpDrawItemStruct->rcItem, DT_SINGLELINE | DT_VCENTER | DT_CENTER);
SetBkMode(lpDrawItemStruct->hDC, TRANSPARENT);
}
dc.Detach();
}
可以參考:http://blog.sina.com.cn/s/blog_65cab32d01013uad.html