Static control set text color
Asked Answered
B

1

7

I have a static control:

HWND hLabelControl=CreateWindowEx(WS_EX_CLIENTEDGE,"STATIC","",
            WS_TABSTOP|WS_VISIBLE|WS_CHILD|SS_CENTER,0,0,24,24,
        hwnd,(HMENU)hS1,GetModuleHandle(NULL),NULL);

I want when a button is pressed the color of the text in the static label to change to red for example.

How can I do this?

I know there is a

SetTextColor(
  _In_  HDC hdc,
  _In_  COLORREF crColor
);

function but I can't figure out how to get the HDC of the static control.

Thanks in advance.

EDIT:

This doesn't work:

        HDC hDC=GetDC(hLabelControl);
        SetTextColor(hDC,RGB(255,0,0));
Buffon answered 11/4, 2013 at 19:30 Comment(2)
The device context is generally given to you in the context of handling the WM_PAINT message.Spiritism
After answering, I realized that this is a duplicate: #14631260Merriott
M
7

Static controls send their parent a WM_CTLCOLORSTATIC message just before they paint themselves. You can alter the DC by handling this message.

case WM_CTLCOLORSTATIC:
  if (the_button_was_clicked) {
    HDC hdc = reinterpret_cast<HDC>(wParam);
    SetTextColor(hdc, COLORREF(0xFF, 0x00, 0x00));
  }
  return ::GetSysColorBrush(COLOR_WINDOW);  // example color, adjust for your circumstance

So the trick is to get the static control to repaint itself when the button is clicked. You can do this several different ways, but the simplest is probably to invalidate the window with InvalidateRect.

Merriott answered 11/4, 2013 at 19:56 Comment(2)
sorry you suggest to put color changing code here, so where the change color procedure is called?????Infelicity
The code snipped I showed would go in the window procedure of the parent of the static control. If you're using a framework like (MFC or WTL) that implements the parent's window procedure for you, you'll have to use whatever mechanism the framework provides to bypass the default handler for that message.Merriott

© 2022 - 2024 — McMap. All rights reserved.