2

How do I change the color of selected text in a RichEdit control, while the text is being selected? SetSysColor() can do it, but that changes the Highlight-color globally.

Setting a CHARFORMAT2 with SCF_SELECTION, and sending a EM_SETCHARFORMAT does change the font and background color. But is only visible once you deselect the same range. That's not really helpful, since I want it to be the original color again once something is deselected.

So, how it's really done puzzles me.

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92

2 Answers2

0

Simply subclass it (posted a long time ago on google groups, C/Winapi code)

  • Non-MFC project... but do you know how MFC manages to do exactly that? –  Jul 21 '09 at 22:33
0

You can start sending event messages for selection changes;

SendMessageW(hWndEdit, EM_SETEVENTMASK, 0, ENM_SELCHANGE);

and then handle the message like this;

case WM_NOTIFY:
    switch (((LPNMHDR)lParam)->code)
    {
    case EN_SELCHANGE:
        SendMessageW(hWndEdit, EM_SETEVENTMASK, 0, ENM_NONE);
        SendMessageW(hWndEdit, EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&format);
        SendMessageW(hWndEdit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&sformat);
        SendMessageW(hWndEdit, EM_HIDESELECTION, 1, 0);
        SendMessageW(hWndEdit, EM_SETEVENTMASK, 0, ENM_SELCHANGE);
        break;
    }

However this will cause some flickering in case of rapid selection changes. It's weird how win32 API produces great amount of problems to deal with whenever you try to customize something.

xuurcanx
  • 1
  • 1