直接进入正题:
在RichEdit中实现关键字高亮的简单方法。
如果要真正实现RichEdit的关键字高亮,那么基本需要把整个RichEdit控件都重写一遍,需要很大的工作量。
既然不想花太大的力气实现,那实现出来的效果多少会有些差别。
在这里,实现的方式是在RichEdit中边输入边接收信息,逐一和已存的关键字比对。
首先先将RichEdit创建出来:
RichEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("RichEdit20A"),NULL, ES_MULTILINE | WS_CHILD |WS_VISIBLE |WS_VSCROLL |WS_HSCROLL | ES_WANTRETURN, 170, 80, rcClient.right-180, rcClient.bottom/2-60, hWnd, 0, hInstance, NULL);
在这之前不要忘记加上RichEdit的头文件 #include "RichEdit.h"和 hInst = LoadLibrary(TEXT("RICHED20.dll"));
由于要对RichEdit中的内容进行动态的改变,所以需要一个新的窗口回调函数:
char buffer[1024 *10]; //设置一个缓冲区,存放所接收到的字符
LRESULT CALLBACK EditProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
HDC hdc;
DWORD FirstChar;
RECT rect;
TEXTRANGE txtrange;
char keybuffer[1024];
HRGN hRgn;
HRGN hOldRgn;
RECT RealRect;
LRESULT nRet;
switch(message)
{
case WM_PAINT:
{
nRet = CallWindowProc((WNDPROC)OldProc,hWnd,message,wParam,lParam);
hdc = GetDC(hWnd);
SendMessage(hWnd,EM_GETRECT,0,(LPARAM)&rect);
LRESULT nPos = SendMessage(hWnd,EM_CHARFROMPOS,0,(LPARAM)&rect);
LRESULT nLine = SendMessage(hWnd,EM_LINEFROMCHAR,nPos,0);
LONG nIndex = SendMessage(hWnd,EM_LINEINDEX,nLine,0);
txtrange.chrg.cpMin = nIndex;
FirstChar = nIndex;
LONG nNextPos = SendMessage(hWnd,EM_CHARFROMPOS,0,(LPARAM)&rect.right);
txtrange.chrg.cpMax = nNextPos;
RealRect.left = rect.left;
RealRect.top = rect.top;
RealRect.right = rect.right;
RealRect.bottom = rect.bottom;
hRgn = CreateRectRgn(RealRect.left,RealRect.top,RealRect.right,RealRect.bottom);
hOldRgn = (HRGN)SelectObject(hdc,hRgn);
txtrange.lpstrText = buffer;
SendMessage(hWnd,EM_GETTEXTRANGE,0,(LPARAM)&txtrange);
int i =0 ,j;
while(buffer[i] != '\0' ) //进行关键字匹配
{
while(buffer[i] != '\0' &&(buffer[i] ==' ' || buffer[i] == '\r' || buffer[i] =='\t' ||
buffer[i] == '\n' || buffer[i] == '(' || buffer[i] == ')'))
i++;
if(buffer[i] == '\0')
break;
for(j=0;buffer[i] != '\0' && buffer[i] !=' ' && buffer[i] != '\r' && buffer[i] !='\t' && buffer[i] != '\n' && buffer[i] != '(' && buffer[i] != ')'; i++,j++)
keybuffer[j] = buffer[i];
keybuffer[j]='\0';
if(Check(keybuffer)==1) //对已存的关键字进行逐一比对
{
SetTextColor(hdc,RGB(0,0,255));
int nWidth = SendMessage(RichEdit,EM_POSFROMCHAR,nIndex+i-j, 0);
rect.left = LOWORD(nWidth) ;
rect.top = HIWORD(nWidth);
DrawText(hdc,keybuffer,-1,&rect,0);
}
}
SelectObject(hdc,hOldRgn);
DeleteObject(hRgn);
ReleaseDC(hWnd,hdc);
}
break;
default:
return CallWindowProc((WNDPROC)OldProc, hWnd, message, wParam, lParam);
}
return nRet;
}
在初始化的时候进行下面的调用即可实现基本的关键字高亮:
OldProc = SetWindowLong(RichEdit, GWL_WNDPROC, (LONG)EditProc);//OldProc为全局LONG类型的变量
注:
关键字为自己设定,在我上边的例子中在Check(char *str)这样的函数进行对已存的关键字进行匹配。