VC RichEdit中英文关键字标红

最近需要做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(255,0,0);

    richFileContext.GetWindowText(m_richText);

    if(m_richText.GetLength()<=0 || strKeyword.GetLength()<=0)
    {
        return;
    }
    
    char *pstrRichText = m_richText.GetBuffer(0);
    char *pstrKeyword = strKeyword.GetBuffer(0);
    wchar_t w_richtext[100]={0},w_keyword[100]={0};
    MByteToWChar(pstrRichText,w_richtext,sizeof(w_richtext)/sizeof(w_richtext[0]));
    MByteToWChar(pstrKeyword,w_keyword,sizeof(w_keyword)/sizeof(w_keyword[0]));
    wchar_t *p = wcsstr(w_richtext,w_keyword);
    while(p)
    {
        int nIndex = p-w_richtext;
        int selIndex = nIndex;
        
        //每换行一次selIndex需要减1,不知道为啥,反复debug出的经验
        for(int i=1;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(-1,-1);

        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, 0, lpcszStr, -1, NULL, 0);

    if(dwSize < dwMinSize)
    {
        return FALSE;
    }


    // Convert headers from ASCII to Unicode.
    MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, lpwszStr, dwMinSize);  
    return TRUE;
}

 

posted on 2013-07-02 12:52  dflower  阅读(627)  评论(0编辑  收藏  举报