Link to home
Start Free TrialLog in
Avatar of abalkur
abalkur

asked on

Setting of Color in MFC

I have a dialog box. i want to know how to set background and foreground colors in a dialog box in MFC. i don't want the default grey colour.Please advise.
ASKER CERTIFIED SOLUTION
Avatar of Paul Maker
Paul Maker
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of captainkirk
captainkirk

You can set the background color by using CWinApp::SetDialogBkColor() in your InitInstance()....

To set both, you may need to override OnCtlColor() for your dialog and call CDC::SetTextColor() and CDC::SetBkColor() there...
In my experience, sometimes just calling the functions to change the color is not sufficient.  This may depend on whether you're trying to color the whole dialog or just dialog controls.  Everything will appear to work correctly, but the dialog controls will still be the default color.  In some cases, this is because one must provide a brush to draw the dialog background with.

Consider this code:

class CSomeClass : public CDialog
{
public:
  CSomeClass();
  ~CSomeClass();

  // Overrides
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(CSomeClass)
    virtual BOOL OnInitDialog();
  //}}AFX_VIRTUAL

  protected:
    // Generated message map functions
    //{{AFX_MSG(CSomeClass)
      afx_msg HBRUSH OnCtlColor(CDC* pDC,
        CWnd* pWnd, UINT nCtlColor);
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()

    HBRUSH m_backBrush;
};

BEGIN_MESSAGE_MAP(CSomeClass, CDialog)
  //{{AFX_MSG_MAP(CSomeClass)
  ON_WM_CTLCOLOR()
  //}}AFX_MSG_MAP
END_MESSAGE_MAP()

BOOL CSomeClass::OnInitDialog()
{
  CDialog::OnInitDialog();

  m_backBrush = CreateSolidBrush(0x00A0C080);
}

HBRUSH CCallingWnd::OnCtlColor(CDC* pDC, CWnd* pWnd,
                               UINT nCtlColor)
{
  HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
     
  pDC->SetBkColor(0x00A0C080);
  hbr = m_backBrush;
  return(hbr);
}

  Basically, this code creates a brush for the dialog when the dialog is created, and then when the system goes to color the dialog controls (say the background for a static text box), it uses SetBkColor() to set the background color for that control *and* also changes the brush to match.  You can also have it check which control is being colored and you can use/return separate colors for each control in the same dialog, which is kind of nice.
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Answered by : makerp

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Roshan Davis
EE Cleanup Volunteer