Changing the Background Color of Edit Controls

.


Click here for larger image

This is the 2nd revision to the original article. I would like to thank everyone who posted comments and any answers to those comments that I've used in this latest revision.


Click here for larger image

If you need to change the background color of CEdit controls on your dialog, it is very simple ! (you don't need to derive your own class from CEdit).

The following example will change the appearance of specific CEdit controls including:

  1. Background color.
  2. Text color.
  3. Transparency.

I chose Blue and Red backgrounds with White text for this example.

In your CTestDlg header file, declare member variables from CBrush and COLORREF:

class CTestDlg : public CDialog
{
protected:
 CBrush m_redbrush,m_bluebrush;
 COLORREF m_redcolor,m_bluecolor,m_textcolor;
};

Then, add these lines in the OnInitDialog function:

BOOL CTestDlg::OnInitDialog()
{
 m_redcolor=RGB(255,0,0);                      // red
 m_bluecolor=RGB(0,0,255);                     // blue
 m_textcolor=RGB(255,255,255);                 // white text
 m_redbrush.CreateSolidBrush(m_redcolor);      // red background
 m_bluebrush.CreateSolidBrush(m_bluecolor);    // blue background
}

Finally do this on the ID_CTLCOLOR handle:

HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
  HBRUSH hbr; 

  switch (nCtlColor) 
  { 
  // process my edit controls by ID.
  case CTLCOLOR_EDIT:
  case CTLCOLOR_MSGBOX:
    switch (pWnd->GetDlgCtrlID())
    {     
  // first CEdit control ID
    case IDC_MYCONTROLNAME1:         // put your own CONTROL ID
                                     // here
      pDC->SetBkColor(bluecolor);    // change the background
                                     // color [background colour
                                     // of the text ONLY]
      pDC->SetTextColor(textcolor);  // change the text color
      hbr = (HBRUSH) m_bluebrush;    // apply the blue brush
                                     // [this fills the control
                                     // rectangle]
      break;   
    // second CEdit control ID
    case IDC_MYCONTROLNAME2:         // make the TEXT transparent,
                                     // but control is still
                                     // filled with the brush
                                     // color!
      pDC->SetBkMode(TRANSPARENT);   // make background
                                     // transparent [only affects
                                     // the TEXT itself]
      pDC->SetTextColor(textcolor);  // change the text color
      hbr = (HBRUSH) m_redbrush;     // apply the red brush
                                     // [this fills the control
                                     // rectangle]
      break;
    case IDC_MYCONTROLNAME3:         // Make the text and the
                                     // control rectangle
                                     // transparent, so the
                                     // dialog window
                                     // color/bitmap draws
                                     // through.
      pDC->SetBkMode(TRANSPARENT);   // make background
                                     // transparent [only affects
                                     // the TEXT itself]
      pDC->SetTextColor(textcolor);  // change the text color
      hbr = m_brush;                 // Return handle to our
                                     // CBrush object [this is
                                     // the brush you've used to
                                     // paint the dialog window.
      break;
    // otherwise, do default handling of OnCtlColor
    default: 
      hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor); 
      break;
    }  
    break;
  // process Static text, READONLY controls, DISABLED * controls.
  // * NOTE: Disabled controls can NOT have their text color
  //         changed.
  //         Suggest you change all your DISABLED controls to
  //         READONLY.
  case CTLCOLOR_STATIC:
    // process my edit controls by ID
    switch (pWnd->GetDlgCtrlID())
    {     
    // one of my READONLY edit controls (could also be disabled or
    // static text)
    case IDC_MYCONTROLNAME4: 
      pDC->SetBkColor(bluecolor);   // change the background color
      pDC->SetTextColor(textcolor); // change the text color
      hbr = (HBRUSH) m_bluebrush;   // apply the brush
      break;
    // otherwise, do default handling of OnCtlColor
    default:
      hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
    }
    break;
  // otherwise, do default handling of OnCtlColor
  default:
    hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
  }

  return hbr; // return brush
}

I hope this code helps you as much as other articles on CodeGuru have helped me.

Miscellaneous Notes/Comments:

Windows CE, READONLY controls: [posted by Tony].
Code works great in EVC++/MFC app. However, for read-only edit boxes, use CTLCOLOR_BTN instead of CTLCOLOR_STATIC in the test of nCtlColor.

READONLY and DISABLED controls are processed using CTLCOLOR_STATIC!

If your controls are set to DISABLED, then you CAN NOT alter the text color; if you want this ability, change all your DISABLED controls to READONLY.

TRANSPARENCY: pDC->SetBkMode(TRANSPARENT;)DOES NOT MAKE THE WHOLE CONTROL TRANSPARENT! it only affects the text itself.
Think of it this way: The control rectangle is filled using the BRUSH, then the text is drawn on top using a background and foreground color. So, to make the entire control transparent, you need to use the above SetBkMode command, and also set the controls brush to the same brush you have used to draw the window itself.

Brief Example:

  1. Add a bitmap resource to your project.
  2. In your class header add a CBitmap variable, such as:
  3. class CMyDialog : public Dialog
    {
    public:
      CBitmap bitmapBackground;
    ...
    
  4. In your class source, load the bitmap up in OnInitDialog:
  5. BOOL CMyDialog::OnInitDialog()
    {
      bitmapBackground.Attach(Loadbitmap(AfxGetInstanceHandle(),
    MAKEINTRESOURCE(IDB_BACKGROUND) ) );
    ...
    
  6. Add OnEraseBkgnd to your class:
  7. BOOL CMyDialog::OnEraseBkgnd(CDC * pDC)
    {
      // center the bitmap in the window
      CRect rect;GetClientRect(&rect);
    
      CDC dc; dc.CreateCompatibleDC(pDC);
      CBitmap * pOldBitmap = dc.SelectObject(&bitmapBackground);
      BITMAP bitmap; bitmapBackground.GetObject(sizeof(BITMAP),
             &bitmap);
    
      int x=(rect.Width()-bm.bmWidth)/2+rect.left;
      int y=(rect.Height()-bm.bmHeight)/2+rect.top;
      pDC->BitBlt(x,y,bm.bmWidth,bm.bmHeight,&dc,0,0,SRCCOPY);
      // center the bitmap
    
      // you could stretch the bitmap to fill the window!
      // pDC->StretchBlt(rect.left,rect.top,rect.Width(),
                         rect.Height(),&dc,0,0,bm.bmWidth,
                         bm.bmHeight,SRCCOPY);
    
      dc.SelectObject(pOldBitmap);
      pDC->SetBkMode(oldbackmode);
    
      return TRUE;
    }
    
  8. Write your custom OnCtlColor handler:
  9. HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd,
                                UINT nCtlColor)
    {
      HBRUSH hbr;
    
      switch (nCtlColor)
      { 
      // process my edit controls by ID.
      case CTLCOLOR_EDIT:
      case CTLCOLOR_MSGBOX:
        switch (pWnd->GetDlgCtrlID())
        {
        // first CEdit control ID
        case IDC_MYCONTROLNAME1:
    // put your own CONTROL ID here
          pDC->SetBkMode(TRANSPARENT);  // make text
                                        // background transparent
          pDC->SetTextColor(RGB(255,0,0));
    // change the text color to red.
          hbr = (HBRUSH) GetStockObject(NULL_BRUSH);
    // apply a null brush, so control's rectangle
    // isn't filled.
          break;
    // otherwise, do default handling of OnCtlColor
      default:
          hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
      }
    
      return hbr;    // return brush
    }
    

Further Reading:

Colored/Blinking Controls and Dialogs with any Font by Yury Goltsman.

History:

Original article posted: March 13, 2001
Date Last Updated: May 19, 2003



Comments

  • Nous comprenons l'ouragan de sable a causé défis add up to known be revealed on down in buckets beaucoup de nos clients Jordan

    Posted by Vetriatszy on 03/15/2013 12:14pm

    grab a system of which invites potential partners like it or cold, using a rediculous amount of muscle can provide a corny go. certainly, in cases where older women continue to be questioned these types of learn a lot muscular body a huge turnoff. It is challenging to look "GQ" possibly "waist" with regard to many muscle mass that are on your structure. if you've got a whole lot of muscle tissue that fat loss wear a regular two of pants, simply read on. gals wish Men having typically levels of muscle tissue, and then fabulous sound. these kinds of guys many surely have another thing in accordance. ladies have a rate levels of lean muscle. they even teach to maintain their body fat ranges horrible in order to exhibit among fine muscle tone. this type of your body sounds large with actually require the latest outfits. are you workouts To astonish various many men while part of physical fitness? i am aware of this specific does seem ridiculous, yet unfortunately absolutely,it is my opinion essentially the real belief that men try acquire as often mass and often. gentlemen is very competitive of course, so they experience the competing in the same room while working out fixing and. The youngster gentlemen get the some older guy using monstrous arm holes, using all over big names and shortly any develops distinct purpose style. each goes on a quest to gain much muscle tissue as we can, require discovering that doable a good check out. Don't get caught up at the "mass" trap so you can get more Women! it really is easy to get drawn straight into the trip using obtaining the most muscular mass that they can. important lads get many of esteem during a workout session. you will youth adult men kissing up to the important wealth weight room in the us. In the outside it's not necessarily the same. brides in particular think these guys hunt laid-back. you only need to just can't check incredible and has many muscular body at once! if you happen to try to wear well put together look at this web-site or just hip sweaters something looks a bit "going

    Reply
  • How to change the background color of Combo Box?

    Posted by srihariram on 06/06/2007 03:37am

    Hi, Could any one suggest the way to change the background color and text color of Combo box. When i change the overload OnCtlColor, to change the background color of the dialog box, even the background color of the Combo box changes. how to overcome this. I am using VS2005 IDE.

    Reply
  • How to change the background color of Combo Box?

    Posted by srihariram on 06/05/2007 08:19am

    Hi, Could any one suggest the way to change the background color and text color of Combo box. When i change the overload OnCtlColor, to change the background color of the dialog box, even the background color of the Combo box changes. how to overcome this. I am using VS2005 IDE.

    Reply
  • Different lines colour in edit box

    Posted by Legacy on 03/17/2003 12:00am

    Originally posted by: Eyal B

    Well ,
    Is it possible to colour lines in different colour ????

    Reply
  • The code throws up unhandled exception

    Posted by Legacy on 02/19/2003 12:00am

    Originally posted by: MATT

    hi the example was brilliant however it terminates my application after my dialog box is closed

    throwing out an unhandled exception

    does anyone know how to solve this please help.

    Reply
  • Changing Bkgd color for Read-Only CEdit in Windows CE

    Posted by Legacy on 01/28/2003 12:00am

    Originally posted by: Tony

    Code works great in EVC++/MFC app. However, for read-only edit boxes, use CTLCOLOR_BTN instead of CTLCOLOR_STATIC in the test of nCtlColor.

    • I want Source

      Posted by palani_svk on 09/07/2004 07:56am

      Nice Application

      Reply
    Reply
  • making this function work with BN_CLICKED Function

    Posted by Legacy on 12/19/2002 12:00am

    Originally posted by: Joe

    I've been trying to change the colors of an edit box after a mouse click on a button, but I have no idea what function I would have to use

    Reply
  • Many thanks for the feedback ... working on a updated article

    Posted by Legacy on 12/13/2002 12:00am

    Originally posted by: Duncan Weir

    Thanks to you all for your feedback.

    I am now working on an updated version of this article, with better explanations of how to get it working, and also to incorporate new features (As asked for), and workarounds for problems that you've already posted here in answer to other queries.

    No ETA for completion, but hope to have it done before Xmas (2002).

    Reply
  • How to change text color in Windows CE

    Posted by Legacy on 10/17/2002 12:00am

    Originally posted by: Romin

    How can we do this in Windows CE ?
    There is no ID_CTLCOLOR handle in Windows CE.
    Please help..

    Reply
  • Changing text color on the fly

    Posted by Legacy on 10/16/2002 12:00am

    Originally posted by: Jared

    How can I adapt this code so that while the user is typing the text color changes (depending on certain characters near the start, ie. '/' - green text "//" - yellow ";2;" - orange

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

Most Popular Programming Stories

More for Developers

RSS Feeds