我想向 RichEdit 控件添加彩色文本行。但是我面临的问题是颜色更改不仅限于我选择的文本。我所做的是:
获取当前光标pos ->插入文本->获取光标pos->选择范围->着色->取消选择
出于某种原因,它似乎也更改了默认颜色。我试图保存旧CHARFORMAT
并在我着色后恢复它(SCF_DEFAULT
并用最后一个字符SCF_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);
}
据我所知,文档 dwEffects 必须设置为 CFE_AUTOCOLOR 或其他有效值。
我找到了一种解决方法,至少对我有用。当我第一次尝试保存/备份和恢复旧CHARFORMAT
时,我没有指定CHARFORMAT cf_old
CFM_COLOR
。现在我使用:
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 格式。