Changing background color of a Dialog

Derive a class from CDialog and add this member variable.

private:

CBrush m_bkBrush; 

Now by using Class Wizard, add a new handler for WM_CTLCOLOR message. and write this code.

HBRUSH CColorDlgDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 

{

HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

switch ( nCtlColor )

{

case CTLCOLOR_EDIT:

case CTLCOLOR_MSGBOX:

case CTLCOLOR_BTN:

case CTLCOLOR_STATIC:

pDC->SetTextColor(RGB(0, 255, 0));

pDC->SetBkColor(RGB(0, 0, 0));

return (HBRUSH)(m_bkBrush.GetSafeHandle());

case CTLCOLOR_DLG:

return static_cast ( m_bkBrush.GetSafeHandle() );

}

// TODO: Return a different brush if the default is not desired

return hbr;

}

Now add three buttons and name them Yellow, Green, and Red and write this code on OnClick message for these buttons.

Here is how your dialog looks like after clicking button1, button2 and button3..

     

 

void CColorDlgDlg::OnButton1() 

{

m_bkBrush.DeleteObject();

m_bkBrush.CreateSolidBrush( RGB ( 255, 255, 0 ) );

Invalidate(TRUE);

}

void CColorDlgDlg::OnButton2() 

{

m_bkBrush.DeleteObject();

m_bkBrush.CreateSolidBrush( RGB ( 0, 255, 0 ) );

Invalidate(TRUE);

}

void CColorDlgDlg::OnButton3() 

{

m_bkBrush.DeleteObject();

m_bkBrush.CreateSolidBrush( RGB ( 255, 0, 0 ) );

Invalidate(TRUE);

}

Run the application and click these buttons.