News | Articles | Libraries | Developer Tools | Books | Forum Links | Search   
Sections:
 

QA: How to create a colored button?

By Nicholas Tsipanov, April 24, 2002.
Print version

Question

I would like to have the buttons in my MFC application have the custom color. How could I do that?

Answer

You need to handle WM_CTLCOLOR in your button's parent window. MFC Wizard will create that handler for you. The framework will ask for color of every control in your window, you need to filter the requests for you control only.

HBRUSH CTestColorButtonDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (CTLCOLOR_BTN == nCtlColor) { if (pWnd == &m_button) { return CreateSolidBrush(RGB(255,0,0)); } } return hbr; }

After you've done this you face the problem with non-default behaviour of MFC buttons To workaround it create a simple CButton subclass that only overrides buggy OnLButtonDown behaviour:

//FixedButton.h: class CFixedButton : public CButton { public: // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSkinnedButton) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CFixedButton) afx_msg void OnLButtonDown(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //FixedButton.cpp: BEGIN_MESSAGE_MAP(CFixedButton, CButton) //{{AFX_MSG_MAP(CFixedButton) ON_WM_LBUTTONDOWN() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CFixedButton::OnLButtonDown (UINT nState, CPoint point) { Default(); }

Use CFixedButton class in your dialog or window whenever you need to non-standard behaviour of the button such as using custom color.

Sample

You can download a sample application (12 Kb) that shows implementing of a colored button.

Discuss

Discuss this article. Here you can write your comments and read comments of other developers.
Rate this article:     Poor Excellent    
 12345 
© 2001-2005 Pocket PC Developer Network, a division of Spb Software House