如何在 mfc 中更改静态文本控件的背景颜色(按下按钮或计时器时)?
我知道它可以用 OnCtlColor() 来完成,但是它会在加载表单并且要绘制静态文本时改变颜色,我想在加载表单之后执行它,也许有一个计时器,我搜索了寻求解决方案,但我没有找到明确的解决方案,这就是我写的:
I know it can be done with OnCtlColor(), but it changes colors when the form is being loaded and the static texts are to be drawn, I want to do it after form is loaded, with a timer maybe, I searched for a solution but I didn't find a clear one, this is what I wrote:
void CTabFive::OnBnClickedButton1()
{
// TODO: Add your control notification handler code here
CWnd* pWnd = this->GetDlgItem(IDC_Chromosome1);
CDC* dc = pWnd->GetDC();
dc->SetBkColor(RGB(200,0,0));
pWnd->Invalidate();
pWnd->UpdateWindow();
Invalidate();
UpdateWindow();
//flag = true;
}
推荐答案
不需要计时器.在这里,我有一个初始化为 false 的类的 bool m_coloured 成员,并在按下按钮时切换.OnCtlColor 将根据 m_coloured 的值绘制为红色或系统颜色.效果很好.
No timer is needed. Here I have a bool m_coloured member of the class initialized to false, and toggled in the button press. The OnCtlColor will draw in red or in the system colour depending on the value of m_coloured. Works nicely.
HBRUSH Cmfcvs2010Dlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
if (nCtlColor == CTLCOLOR_STATIC && pWnd->GetDlgCtrlID() == IDC_LABEL)
{
DWORD d = GetSysColor(COLOR_BTNFACE);
COLORREF normal = RGB(GetRValue(d), GetGValue(d), GetBValue(d));
COLORREF red = RGB(255, 0, 0);
pDC->SetBkColor(m_coloured ? red : normal);
}
return hbr;
}
void Cmfcvs2010Dlg::OnBnClickedButton1()
{
m_coloured = !m_coloured;
Invalidate();
}
相关文章