
How do you set the background color of a CEdit control
Quote:
> Any suggestions?
> Thanks
> Mike
Text from an article that may be useful to you appears below...
Cecil
/////////////////////
There are instances where you might have multiple edit controls in a
dialog box, but want
only one of the controls to have a different background
color. This article shows how to
accomplish that. The technique applies to other types of
controls as well.
This example assumes that you have created a red brush
(m_Brush) at such a place in your
code that the brush will have an adequate lifetime. It is
also assumed that you are
responsible for deleting the brush object and freeing up any
memory that the brush required.
Using Class Wizard, implement a handler for the WM_CTLCOLOR
message in your dialog
object.
HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT
nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd,
nCtlColor);
return hbr;
// TODO: Return a different brush if the
default is not desired
// return hbr;
}
Check the value of nCtlColor against CTLCOLOR_EDIT and the
handle of the window pointed
to by pWnd against the handle of the edit control which
color you want to change. The trick
is to use the window handles for the comparison rather than
the pointers because the
pointers are temporary - sometimes too temporary - but the
handles are permanent.
HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT
nCtlColor)
{
// get a pointer to the specific edit control which
color you want to control
CEdit * pEdit = (CEdit
*)GetDlgItem(IDC_REDEDIT);
if(nCtlColor == CTLCOLOR_EDIT &&
pEdit->GetSafeHwnd() == pWnd->GetSafeHwnd()) {
// set the back mode so that new background color
shows through the text
pDC->SetBkMode(TRANSPARENT);
// make the text white so that it shows up well over
red
pDC->SetTextColor(RGB(255,255,255));
// return the red brush
return m_Brush;
}
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd,
nCtlColor);
return hbr;
}
This approach will work with edit controls that are
designated as READONLY by comparing
nCtlColor with CTLCOLOR_STATIC rather than CTLCOLOR_EDIT.
You should also set the
text back color to an appropriate color rather than setting
the back mode to TRANSPARENT.
HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT
nCtlColor)
{
// get a handle to the specific READ ONLY edit
control which color you want to control
CEdit * pEditReadOnly = (CEdit
*)GetDlgItem(IDC_READONLYEDIT);
HWND hWndReadOnly =
pEditReadOnly->GetSafeHwnd();
if(nCtlColor == CTLCOLOR_STATIC &&
hWndReadOnly == pWnd->GetSafeHwnd()) {
// set the text back color to the same as the brush
(red)
pDC->SetBkColor(RGB(255,0,0));
// make the text white so that it shows up well over
red
pDC->SetTextColor(RGB(0,0,255));
// return the red brush
return m_Brush;
}
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd,
nCtlColor);
return hbr;
}
///////////////////////////////////////////
--
Cecil Galbraith
Free programmer's utilities and MFC tips at
http://www.concentric.net/~cgalbrai