How to make a colored button

22 01 2012

We cannot directly change the default color of push buttons in VC++ applications. WM_CTLCOLOR does  not work for push buttons. 😦  Then how can we set our own color for push buttons.

The only way to change the color for push buttons is to use owner-draw button control. That means we have to change the style of the push button to Owner draw. Then within the WM_DRAWITEM message handler we can decide what drawing action is required for our controls.

afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct);
The first parameter is the id of the control that sent the WM_DRAWITEM message and the second parameter pointing to DRAWITEMSTRUCT structure that contains information about the item to be drawn and the type of drawing required.

 

 

void CMyDialog::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	if(nIDCtl==IDC_BUTTON_COLOR)
	{
		CDC dc;

		dc.Attach(lpDrawItemStruct ->hDC);
		RECT rect;
		rect= lpDrawItemStruct ->rcItem;

		dc.FillSolidRect(&rect,RGB(0,255,0));
		UINT state=lpDrawItemStruct->itemState;

		if((state & ODS_SELECTED))
		{
			dc.DrawEdge(&rect,EDGE_SUNKEN,BF_RECT);

		}
		else
		{
			dc.DrawEdge(&rect,EDGE_RAISED,BF_RECT);
		}

		dc.SetBkColor(RGB(100,100,255));
		dc.SetTextColor(RGB(255,0,0));
		dc.SetBkMode( TRANSPARENT );

		TCHAR buffer[MAX_PATH];
		ZeroMemory(buffer,MAX_PATH );
		::GetWindowText(lpDrawItemStruct->hwndItem,buffer,MAX_PATH);
		dc.DrawText(buffer,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE);

		dc.Detach();
	}				

	CDialog::OnDrawItem(nIDCtl, lpDrawItemStruct);
}

Don’t forget to set Owner Draw property of the control as true form the IDE property section of the controls.