I have a simple MFC dialog based application which contains a static text control among other basic controls like check boxes controls and buttons and a edit box control (see photo). I want to be able to change the colour of the static text control dynamically when a user clicks on the GO button. I've borrowed most of the code below from other SO posts.
I've implemented the following WM_CTLCOLOR
message handler as follows:
HBRUSH CFileRenamerDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
CWnd* pWndT = pWnd->GetDlgItem(IDC_STATIC);
// TODO: Change any attributes of the DC here
switch (nCtlColor)
{
case CTLCOLOR_STATIC:
if (pWnd->GetDlgCtrlID() == IDC_STATIC)
{
pDC->SetTextColor(RGB(255, 0, 0));
//MessageBoxW(L"TEST", L"TESTING", 0);
return (HBRUSH)GetStockObject(NULL_BRUSH);
}
}
return hbr;
}
void CFileRenamerDlg::OnBnClickedGo()
{
CWnd* pWnd = this->GetDlgItem(IDC_STATIC);
CDC* dc = pWnd->GetDC();
dc->SetTextColor(RGB(128, 128, 128));
//COLORREF ref = dc->GetTextColor();
pWnd->Invalidate(0);
pWnd->UpdateWindow();
}
The above code does work as the colour of the static text control does change to the colour specified above but when I try the code written within the OnBnClickedGo()
handler it does not work. No errors or debug assertion failure of the sort. How can I change the colour of the static text to anything else ?
[SOLVED] Just to shed some light as to where the problem lied. I read a post here and here suggesting that the default control ID in resource editor of the static text control should be changed from the default control ID of ID_STATIC
to something else such as ID_STATIC_TEXT
now all is working. I hope this helps someone else having similar issues. I've posted working code that toggles the color of the static text control.
HBRUSH CFileRenamerDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
static int nColor = 0x0;
int rgbRedC = 0x000000FF;
int rgbGreenC = 0x0000FF00;
int rgbBlueC = 0x00FF0000;
int regbBlackC = 0x00000000;
// TODO: Change any attributes of the DC here
switch (nCtlColor)
{
case CTLCOLOR_STATIC:
if (pWnd->GetDlgCtrlID() == IDC_STATIC_TEXT)
{
if (nColor == regbBlackC)
{
pDC->SetTextColor(RGB(0, 0, 255));
nColor = rgbBlueC;
}
else if (nColor == rgbBlueC)
{
pDC->SetTextColor(RGB(255, 0, 0));
nColor = rgbRedC;
}
}
return hbr;
}
void CFileRenamerDlg::OnBnClickedGo()
{
CWnd* pWnd = this->GetDlgItem(IDC_STATIC_TEXT);
pWnd->Invalidate(0);
}