query
query

Reputation: 381

Change a text color for the checkbox after mouse click

I am using win32 API (not MFC).

I have a dialog with a checkbox. I want to change the color of the checkbox label.

case WM_COMMAND:          
      if (LOWORD(wParam) == IDC_CHECKBOX)
      {
         HWND hCheck = GetDlgItem(hDlg, LOWORD(wParam));
         bool checked = (int)SendMessage(hCheck, BM_GETCHECK, 0, 0);
         
         if (checked)
         {
           HDC hDc = GetDC(hCheck);
           SetTextColor(hDc, RGB(255, 0, 0));
           return (LRESULT)GetStockObject(NULL_BRUSH);
         }
      }
      break;           

The code doesn't work as after clicking on the checkbox, the color is still the same. I am wondering if my changes get overwritten during the redraw of the dialog.

Thanks for help.

Upvotes: 0

Views: 453

Answers (1)

Strive Sun
Strive Sun

Reputation: 6289

You can use WM_CTLCOLORSTATIC to change the color of the checkbox label.

Some code:

bool checked;
HWND hCheck = CreateWindowEx(0, L"BUTTON", L"text", WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, 150, 100, 60, 20, hWnd, (HMENU)IDC_CHECKBOX, (HINSTANCE)GetWindowLong(hWnd, GWLP_HINSTANCE), NULL);
...

case WM_COMMAND:
{
    int wmId = LOWORD(wParam);
    // Parse the menu selections:
    switch (wmId)
    {    
        case IDC_CHECKBOX:
        {
            checked = (int)SendMessage(hCheck, BM_GETCHECK, 0, 0);               
            InvalidateRect(hWnd, NULL, 1);
        }
        break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }
}
break;

case WM_CTLCOLORSTATIC:
{    
    HDC hdc = (HDC)wParam;        
    if ((HWND)lParam == hCheck)
    {
        if (checked)
        {
            SetTextColor(hdc, RGB(255, 0, 0));
            return (LRESULT)GetStockObject(NULL_BRUSH);
        }
        else
        {
            SetTextColor(hdc, RGB(0, 0, 0));
            return (LRESULT)GetStockObject(NULL_BRUSH);
        }
    }
}
break;  

Debug:

enter image description here

Upvotes: 3

Related Questions