最近需要做vc的RichEdit控件里的内容关键字标红,由于RichEdit的内容可能是中英文混合的,所以需要先转成Unicode,再用wcsstr函数找到关键字出现的位置,再用SetSel、SelSelectionCharFormat方法进行标红。

//CString m_richText; RichEdit内容
//CString strKeyword; 关键字
CHARFORMAT cf;
ZeroMemory(&cf, sizeof(CHARFORMAT));
cf.dwMask = CFM_STRIKEOUT|CFM_BOLD | CFM_COLOR;
cf.dwEffects = CFE_BOLD;
cf.crTextColor = RGB(,,); richFileContext.GetWindowText(m_richText); if(m_richText.GetLength()<= || strKeyword.GetLength()<=)
{
return;
} char *pstrRichText = m_richText.GetBuffer();
char *pstrKeyword = strKeyword.GetBuffer();
wchar_t w_richtext[]={},w_keyword[]={};
MByteToWChar(pstrRichText,w_richtext,sizeof(w_richtext)/sizeof(w_richtext[]));
MByteToWChar(pstrKeyword,w_keyword,sizeof(w_keyword)/sizeof(w_keyword[]));
wchar_t *p = wcsstr(w_richtext,w_keyword);
while(p)
{
int nIndex = p-w_richtext;
int selIndex = nIndex; //每换行一次selIndex需要减1,不知道为啥,反复debug出的经验
for(int i=;i<richFileContext.GetLineCount();i++)
{
int lineIndex = richFileContext.LineIndex(i);
if(nIndex>lineIndex)
{
selIndex--;
}
else
{
break;
}
}
//////////////////////////////////////// richFileContext.SetSel(selIndex,selIndex+wcslen(w_keyword));
richFileContext.SetSelectionCharFormat(cf);
richFileContext.SetSel(-,-); p = wcsstr(w_richtext+nIndex+wcslen(w_keyword),w_keyword);
}

其中MByteToWChar如下:

//-------------------------------------------------------------------------------------
//Description:
// This function maps a character string to a wide-character (Unicode) string
//
//Parameters:
// lpcszStr: [in] Pointer to the character string to be converted
// lpwszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szA,szW,sizeof(szW)/sizeof(szW[0]));
//---------------------------------------------------------------------------------------
BOOL MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
{
// Get the required size of the buffer that receives the Unicode
// string.
DWORD dwMinSize;
dwMinSize = MultiByteToWideChar (CP_ACP, , lpcszStr, -, NULL, ); if(dwSize < dwMinSize)
{
return FALSE;
} // Convert headers from ASCII to Unicode.
MultiByteToWideChar (CP_ACP, , lpcszStr, -, lpwszStr, dwMinSize);
return TRUE;
}
05-26 12:40