动态设置Edit控件的背景及字体颜色

 

1.新建一个基于对话框的应用程序,在对话框上添加一个Edit控件和三个Radio控件
2.修改Radio控件的ID分别为:IDC_RAD_RED、IDC_RAD_GREED、IDC_RAD_BLUE,名称对应修改为red、green、blue
3.向对话框对应的类中添加如下成员变量:
public:
 COLORREF m_colorEditText; // edit控件的字体颜色
 COLORREF m_colorEditBK;  // edit控件的背景颜色
 CBrush* m_pEditBkBrush;
并在构造函数中初始化:
CColorEditDlgDlg::CColorEditDlgDlg(CWnd* pParent )
 : CDialog(CColorEditDlgDlg::IDD, pParent)
{
 //{{AFX_DATA_INIT(CColorEditDlgDlg)
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
 
 m_colorEditText = RGB(255,255,255);
 m_colorEditBK = RGB(0,0,0);
 m_pEditBkBrush = new CBrush(RGB(0,0,0));
}
4.向对话框添加WM_CTLCOLOR和WM_DESTORY消息的响应函数如下:
HBRUSH CColorEditDlgDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
 switch (nCtlColor) {
  
 case CTLCOLOR_EDIT:
 case CTLCOLOR_MSGBOX:
  // Set color to green on black and return the background brush.
  pDC->SetTextColor(m_colorEditText);
  pDC->SetBkColor(m_colorEditBK);
  return (HBRUSH)(m_pEditBkBrush->GetSafeHandle());
  
 default:
  return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
 }

 
}

void CColorEditDlgDlg::OnDestroy()
{
 CDialog::OnDestroy();
 
 // TODO: Add your message handler code here
 delete m_pEditBkBrush;
 
}
5.分别向三个Radio控件添加BN_CLICKED消息响应函数如下:
void CColorEditDlgDlg::OnRadRed()
{
 // TODO: Add your control notification handler code here

 m_colorEditText = RGB(255,0,0);

 // redraw edit control
 ((CEdit *)GetDlgItem(IDC_EDIT1))->SetRedraw(TRUE);

 // invalidate the entire control, force painting
 ((CEdit *)GetDlgItem(IDC_EDIT1))->Invalidate();
 ((CEdit *)GetDlgItem(IDC_EDIT1))->UpdateWindow();
 
}

void CColorEditDlgDlg::OnRadBlue()
{
 // TODO: Add your control notification handler code here
 m_colorEditText = RGB(0,0,255);

 // redraw edit control
 ((CEdit *)GetDlgItem(IDC_EDIT1))->SetRedraw(TRUE);
 
 // invalidate the entire control, force painting
 ((CEdit *)GetDlgItem(IDC_EDIT1))->Invalidate();
 ((CEdit *)GetDlgItem(IDC_EDIT1))->UpdateWindow();

}

void CColorEditDlgDlg::OnRadGreen()
{
 // TODO: Add your control notification handler code here
 m_colorEditText = RGB(0,255,0);

 // redraw edit control
 ((CEdit *)GetDlgItem(IDC_EDIT1))->SetRedraw(TRUE);
 
 // invalidate the entire control, force painting
 ((CEdit *)GetDlgItem(IDC_EDIT1))->Invalidate();
 ((CEdit *)GetDlgItem(IDC_EDIT1))->UpdateWindow();

}

完成后运行程序,点击Radio控件可以动态改变编辑框中字体的颜色,如果想改变edit框背景的颜色,可以修改成员变量m_colorEditBK的值并重绘控件。

你可能感兴趣的:(动态设置Edit控件的背景及字体颜色)