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.

Advertisements

Actions

Information

6 responses

28 07 2012
Good name

Thanks! good for me

29 07 2012
Sanoop S P

Thank you.

30 07 2012
Good name

is it work for VC++ 6 ?

31 07 2012
Sanoop S P

Yes.. This will work in VC++ 6.

19 11 2012
Thomas

thank you for the code….works great, best regards Thomas

9 12 2012
Sanoop S P

Thank you Thomas

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: