Click here to Skip to main content
15,880,405 members
Articles / Desktop Programming / MFC
Article

How to change the back color of an edit box when it gets the focus

Rate me:
Please Sign up or sign in to vote.
1.95/5 (17 votes)
10 Jun 2001 180.5K   4.7K   47   15
Change the back color of an edit box to yellow when it gets the focus, and back to white when it loses the focus.

Sample Image - CEditBkColor.gif

Introduction

This article shows how to change the back color of an edit box when it gets the focus.

  1. Derive a class from the standard edit control class, CEdit.
  2. Add 3 private variables:
    • A COLORREF to store the current back color
    • A CBrush to store the brush used to paint the back color of the edit control
    • A CString to store the current contents of the edit box
  3. Override the virtual OnChildNotify function.
    BOOL CMyEdit::OnChildNotify(UINT message, 
        WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
    {
        // We only want to handle WM_CTLCOLOREDIT messages - 32 bit only
        if (message != WM_CTLCOLOREDIT) 
        {
            return CEdit::OnChildNotify(message, wParam, lParam, pLResult);
        }
        HDC hdcChild = (HDC)wParam;
        // Text is black – you can modify this by adding
        // another variable for text color
        SetTextColor(hdcChild, RGB(0,0,0));
        SetBkColor(hdcChild, m_BackColor);
        return TRUE;
    }
  4. Add message handlers to handle the following Windows messages:
    • ON_WM_SETFOCUS
    • ON_WM_KILLFOCUS
    • ON_WM_PAINT
    void CMyEdit::OnSetFocus(CWnd* pOldWnd)
    {
        CEdit::OnSetFocus(pOldWnd);
    
        m_BackColor = RGB(255,255,0);
        Invalidate(FALSE);
    }
    
    void CMyEdit::OnKillFocus(CWnd* pNewWnd)
    {
        CEdit::OnKillFocus(pNewWnd);
        // I am setting normal back color to white
        // – you can modify this as you see fit
        m_BackColor = RGB(255,255,255);
        // Force a repaint
        Invalidate(FALSE);
    }
    void CMyEdit::OnPaint()
    {
        CPaintDC dc(this); // device context for painting
    
        // TODO: Add your message handler code here
        GetWindowText(m_Text);
        SetBkGrndColor();
    
        // Do not call CEdit::OnPaint() for painting messages
    }
  5. Add a private member function SetBkGrndColor()
    void CMyEdit::SetBkGrndColor()
    {
        // Delete the old brush
        m_Brush.DeleteObject();
        // Create a new brush in the specified color
        m_Brush.CreateSolidBrush(m_BackColor);
        CDC* pDC = GetDC();
        pDC->SetBkMode(OPAQUE);
        pDC->SetBkColor(m_BackColor);
        // Select the brush into this window’s device context
        pDC->SelectObject(&m_Brush);
        CRect rc;
        // Get the client area of the edit control
        GetClientRect(&rc);
        ScreenToClient(&rc);
        // Apply the device context to the client area of the edit control
        pDC->Rectangle(0, 0, rc.Width(), rc.Height());
        // Rewrite the text since the backcolor paint
        // overwrote the existing text
        pDC->SetTextColor(RGB(0, 0, 0,));
        pDC->TextOut(2, 2, m_Text.GetBuffer(m_Text.GetLength()));
    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I am a Visual Basic, Visual C++ programmer (consultant) with 6 years experience. I am also an instructor and have been teaching Visual Basic and Visual C++ at a local community college for the past 15 months.

Comments and Discussions

 
Generalin my opinion... Pin
Cho,Dae-Wan27-Mar-04 7:46
Cho,Dae-Wan27-Mar-04 7:46 
Questionhow to change the color of an edit box Pin
bhanusiva29-Jan-04 6:04
bhanusiva29-Jan-04 6:04 
AnswerRe: how to change the color of an edit box Pin
ihoapm23-Dec-04 20:36
ihoapm23-Dec-04 20:36 
GeneralSeems to work without CMyEdit::OnPaint Pin
chris10916-Dec-03 23:55
chris10916-Dec-03 23:55 
GeneralThis article is just cut-n-paste from MSDN Q132080 PinPopular
ip30-Oct-03 21:05
ip30-Oct-03 21:05 
GeneralRe: This article is just cut-n-paste from MSDN Q132080 Pin
Dean Bathke4-Feb-05 18:19
Dean Bathke4-Feb-05 18:19 
GeneralChanging the Selection Color within the control Pin
Chandra Birusumanti12-Aug-03 8:47
Chandra Birusumanti12-Aug-03 8:47 
GeneralQuestion about CEdit Pin
1-Feb-02 8:46
suss1-Feb-02 8:46 
GeneralProblems Pin
Christian Graus11-Nov-01 13:28
protectorChristian Graus11-Nov-01 13:28 
Just thought I'd point out a couple of issues with this code:

Here is my updated version of the painting code:

	// Get the string 
//( why make it a member variable if it's only used in one place ? )
	CString text;
	GetWindowText(text);
	// Delete the old brush
	m_Brush.DeleteObject();
	// Create a new brush in the specified color
	m_Brush.CreateSolidBrush(m_Col);
	CDC* pDC = GetDC();
	pDC->SetBkMode(OPAQUE);
	pDC->SetBkColor(m_Col);
	// Select the brush into this window’s device context
	pDC->SelectObject(&m_Brush);
	CRect rc;
	// Get the client area of the edit control
	GetClientRect(&rc);
// This rect only is queried for it's width & height, so relative pos is irrelevant,
// but either way, ScreenToClient on a client rect ? 
//	ScreenToClient(&rc);
	// Apply the device context to the client area of the edit control
	pDC->Rectangle(0, 0, rc.Width(), rc.Height());
	// Rewrite the text since the backcolor paint overwrote the existing text
// Changed this to ExtTextOut because otherwise it drew past the edit box if the string was too long
	pDC->SetTextColor(RGB(0, 0, 0,));
	pDC->ExtTextOut(2, 2, ETO_CLIPPED, &rc, text.GetBuffer(text.GetLength()), NULL);
// The original code did not release the buffer after getting it.
	text.ReleaseBuffer();


After all that, I still don't have this working the way I want it, I still need to reset the font, which is going bold due to the call to TextOut ( default font is bold ), etc. It's a useful idea though, it just needs some more work.


Christian

After all, there's nothing wrong with an elite as long as I'm allowed to be part of it!! - Mike Burston Oct 23, 2001
GeneralRe: Problems Pin
James R. Twine4-Jan-02 8:16
James R. Twine4-Jan-02 8:16 
GeneralRe: Problems Pin
Christian Graus4-Jan-02 10:50
protectorChristian Graus4-Jan-02 10:50 
GeneralRe: Problems Pin
James R. Twine4-Jan-02 11:01
James R. Twine4-Jan-02 11:01 
GeneralRe: Problems Pin
Christian Graus4-Jan-02 11:10
protectorChristian Graus4-Jan-02 11:10 
GeneralRe: Problems TN062 Pin
osy8-Apr-03 1:28
osy8-Apr-03 1:28 
GeneralMore options Pin
16-Jun-01 9:05
suss16-Jun-01 9:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.