robin.koch
robin.koch

Reputation: 1223

Richedit change color of selection


I want to add a colored text line to a RichEdit control. But I'm facing the problem that the colorchange isn't limited to the text I selected. What I do is:
get current cursor pos -> insert text -> get cursor pos -> select the range -> color it -> unselect
For some reason it seems to change the default color, too. I tried to save the old CHARFORMAT and restore it (SCF_DEFAULT and SCF_SELECTION with the last char) after I colored the line, but that didn't work. Am I missing something?

I got a RichEdit 2.0 and the following function:

hEdit_Console = CreateWindow(RICHEDIT_CLASS, "", 
WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY | WS_VSCROLL, 
10, 100, 260, 120, hWnd, NULL, ((LPCREATESTRUCT) lParam)->hInstance, NULL);
SendMessage(hEdit_Console, WM_SETFONT, (LPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);


void AddInfo2(HWND con, char* text)
{
  CHARFORMAT cf;
  int start, stop;

  memset( &cf, 0, sizeof cf );
  cf.cbSize = sizeof cf;
  cf.dwMask = CFM_COLOR;
  cf.crTextColor = RGB(51, 204, 51);

  SendMessage(con, EM_SETSEL, -1, -1);
  start = SendMessage(con, WM_GETTEXTLENGTH, 0, 0);
  SendMessage(con, EM_REPLACESEL, FALSE, (LPARAM)text);
  stop = SendMessage(con, WM_GETTEXTLENGTH, 0, 0);
  SendMessage(con, EM_SETSEL, start, stop);
  SendMessage(con, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cf);
  SendMessage(con, EM_SETSEL, -1, -1);
}

Upvotes: 1

Views: 1290

Answers (2)

robin.koch
robin.koch

Reputation: 1223

I found a workaround for it, that works at least for me. When I first tried to save/backup and restoring the old CHARFORMAT, I did it without specifying CFM_COLOR for CHARFORMAT cf_old. Now I use:

SendMessage(con, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cf_old);
cf_old.dwMask = CFM_COLOR;
SendMessage(con, EM_SETSEL, -1, -1);
SendMessage(con, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cf);
SendMessage(con, EM_REPLACESEL, FALSE, (LPARAM)text);
SendMessage(con, EM_SETSEL, -1, -1);
SendMessage(con, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cf_old);

It somehow explains why my first try didn't work. It seems that everytime you add something to the RichEdit the CHARFORMAT of the first char before the caret is used.

Upvotes: 0

xMRi
xMRi

Reputation: 15355

As far as I read the documentation dwEffects must be set to CFE_AUTOCOLOR or another valid value.

Upvotes: 2

Related Questions