I want to change the color of an Edit box upon set focus and
set back to normal color as the focus killed as my client want so. Hope this
tricks will help those beginner who want to change their control color.
Here is the process I Have follow
1.
Create a MFC Dialog based project.
2.
Add following control on the dialog
3.
Add two Global variable for the background and
text color and a Static CBrush.
const COLORREF FG_COLOR = RGB(186, 186,
186);
const COLORREF BK_COLOR = RGB(69, 69, 69);
static CBrush bkBrush(BK_COLOR);
4.
Add WM_CTLCOLOR member function and add
following code.
HBRUSH CColorEditDemoDlg::OnCtlColor(CDC*
pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH
hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
if
(nCtlColor == CTLCOLOR_EDIT &&
pWnd->m_hWnd
== ::CWnd::GetFocus()->GetSafeHwnd())
{
pDC->SetBkColor(BK_COLOR);
pDC->SetTextColor(FG_COLOR);
return
bkBrush;
}
return
hbr;
}
5.
Add Setfocus and KillFocus function on
MESSAGE_MAP
BEGIN_MESSAGE_MAP(CColorEditDemoDlg, CDialogEx)
…
ON_CONTROL_RANGE(EN_SETFOCUS,0x0,0xFFFFFFFF,OnEditSetFocus)
ON_CONTROL_RANGE(EN_KILLFOCUS,0x0,0xFFFFFFFF,OnEditKillFocus)
END_MESSAGE_MAP()
6.
Add two member function as on Message map.
OnEditSetFocus and OnEditKillFocus.
void CColorEditDemoDlg::OnEditSetFocus(UINT
nID)
{
RepaintIfEdit(GetDlgItem(nID));
}
void
CColorEditDemoDlg::OnEditKillFocus(UINT nID)
{
RepaintIfEdit(GetDlgItem(nID));
}
7.
Add a member function RepaintIfEdit (if the
focus control is an edit will be repainted.)
void CColorEditDemoDlg::RepaintIfEdit(CWnd*
pWnd)
{
WCHAR
clsName[6] = L"";
GetClassName(pWnd->GetSafeHwnd(),
clsName, 6);
if
(StrCmp(clsName, L"Edit") == 0)
{
pWnd->Invalidate();
pWnd->UpdateWindow();
}
}
Compile and Run.
You can have demo here.
No comments:
Post a Comment