Richedit改变了选择的颜色

时间:2013-10-15 10:27:22

标签: c winapi richedit


我想在RichEdit控件中添加彩色文本行。但我面临的问题是颜色变化不仅限于我选择的文字。我所做的是:
获取当前光标pos - >插入文字 - >获取光标pos - >选择范围 - >给它上色 - >取消选择由于某种原因,它似乎也改变了默认颜色。我尝试保存旧CHARFORMAT并在我对线条进行着色后将其恢复(SCF_DEFAULTSCF_SELECTION与最后一个字符),但这不起作用。我错过了什么吗?

我有一个RichEdit 2.0和以下功能:

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);
}

2 个答案:

答案 0 :(得分:2)

据我所知,documentation dwEffects 必须设置为CFE_AUTOCOLOR或其他有效值。

答案 1 :(得分:0)

我找到了一个解决方法,至少对我有用。当我第一次尝试保存/备份并恢复旧的CHARFORMAT时,我没有为CFM_COLOR指定CHARFORMAT cf_old。现在我使用:

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);

它以某种方式解释了为什么我的第一次尝试不起作用。似乎每次向RichEdit添加一些东西时,使用插入符号之前的第一个char 的CHARFORMAT。