
Introduction
This article shows how to change the back color of an edit box when it gets the focus.
- Derive a class from the standard edit control class,
CEdit
.
- 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
- Override the virtual
OnChildNotify
function. BOOL CMyEdit::OnChildNotify(UINT message,
WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
{
if (message != WM_CTLCOLOREDIT)
{
return CEdit::OnChildNotify(message, wParam, lParam, pLResult);
}
HDC hdcChild = (HDC)wParam;
SetTextColor(hdcChild, RGB(0,0,0));
SetBkColor(hdcChild, m_BackColor);
return TRUE;
}
- 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);
m_BackColor = RGB(255,255,255);
Invalidate(FALSE);
}
void CMyEdit::OnPaint()
{
CPaintDC dc(this);
GetWindowText(m_Text);
SetBkGrndColor();
}
- Add a private member function
SetBkGrndColor()
void CMyEdit::SetBkGrndColor()
{
m_Brush.DeleteObject();
m_Brush.CreateSolidBrush(m_BackColor);
CDC* pDC = GetDC();
pDC->SetBkMode(OPAQUE);
pDC->SetBkColor(m_BackColor);
pDC->SelectObject(&m_Brush);
CRect rc;
GetClientRect(&rc);
ScreenToClient(&rc);
pDC->Rectangle(0, 0, rc.Width(), rc.Height());
pDC->SetTextColor(RGB(0, 0, 0,));
pDC->TextOut(2, 2, m_Text.GetBuffer(m_Text.GetLength()));
}
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