Changing background of text in edit control

12,548

Solution 1

In the parent of the edit control, handle the WM_CTLCOLORSTATIC message, the wParam of this message is the HDC that the Edit control is about to draw with, for most CTLCOLOR messages, if you set text and background colors into this DC, the control will use the colors you set.

You can also return an HBRUSH and the contol will use that for any brush painting that it wil do, but many controls don't use brushes much, so that will have limited effect for some CTLCOLOR messages. Your best bet here is to return the DC brush, and set the DC Brush color to match the BkColor of the DC.

 LRESULT lRet = 0; // return value for our WindowProc.
 COLORREF crBk = RGB(255,0,0); // use RED for Background.

 ... 

 case WM_CTLCOLORSTATIC:
    {
    HDC hdc = (HDC)wParam;
    HWND hwnd = (HWND)lParam; 

    // if multiple edits and only one should be colored, use
    // the control id to tell them apart.
    //
    if (GetDlgCtrlId(hwnd) == IDC_EDIT_RECOLOR)
       {
       SetBkColor(hdc, crBk); // Set to red
       SetDCBrushColor(hdc, crBk);
       lRet = (LRESULT) GetStockObject(DC_BRUSH); // return a DC brush.
       }
    else
       {
       lRet = DefWindowProc(hwnd, uMsg, wParam, lParam);
       }
    }
    break;

Solution 2

WM_CTLCOLORSTATIC is for static text control.

To be simple, you can do this in your winproc:

...
case WM_CTLCOLOREDIT:
{
    HDC hdc = (HDC)wParam;
    SetTextColor(hdc, yourColor);  // yourColor is a WORD and it's format is 0x00BBGGRR
    return (LRESULT) GetStockObject(DC_BRUSH); // return a DC brush.
}
...

If you have more than 1 edit control, you can use the item id and lParam to check which one need to be change.

Solution 3

WM_CTLCOLOREDIT allows you to set text and background color(+brush), if you want more control than that, you have to subclass and paint yourself

Share:
12,548
cpx
Author by

cpx

Updated on June 05, 2022

Comments

  • cpx
    cpx almost 2 years

    Can you change the background of text in area of edit control that would stay static?

  • deLock
    deLock almost 5 years
    Actually, even though it is the accepted answer, it will not work for edit control as the OP asked for. For that to work, one would need to replace WM_CTLCOLORSTATIC by WM_CTLCOLOREDIT.
  • X. Liu
    X. Liu about 4 years
    If the edit control is disabled or read-only, use WM_CTLCOLORSTATIC. For regular edit controls, use WM_CTLCOLOREDIT.