简体   繁体   中英

Changing background of text in edit control

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

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;

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.

WM_CTLCOLOREDIT允许你设置文本和背景颜色(+画笔),如果你想要更多的控制,你必须子类化并自己画画

you could do something like this:

CBrush bkBrush;
RECT ctrlRect;
COLORREF crBk = RGB(255,0,0); // Red color
bkBrush.CreateSolidBrush(crBk);

CWnd* pDlg = CWnd::GetDlgItem(IDC_EDIT);
pDlg->GetClientRect(&ctrlRect);
pDlg->GetWindowDC()->FillRect(&ctrlRec, &bkBrush);
pDlg->GetWindowDC()->SetBkColor(crBk);

This should change the background color of the edit control

All you need is to set the required color in control's device context and pass an HBRUSH with same color in WM_CTLCOLOREDIT message. If you want to change both foreground & background colors, use SetTextColor t0 change the text color. But you must pass the background color HBRUSH. But if you want to change the text color only, then you must pass a DC_BRUSH with GetStockObject function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM