实现编辑框中的文字高亮

文字高亮原理:
1.当编辑框文字变化时,获取当前光标的位置,然后通过光标的坐标和编辑框各字符的坐标比较,从而得到光标此时在字符中的索引;
2.通过索引处理整个字符串,获得光标处的独立字符(即该字符前后都不是字母)并返回该字符的边界索引;
3.获取到文字后,将文字在预设的文字数组里匹配。
3.1如果是关键字,则通过边界索引选中该字符,然后设置选中字符串为高亮色,在将光标移回原处,设回原色;

3.2如果不是关键字;则选中设置回普通颜色;

CArray<CString,CString&> m_aryString;

void CRichEditEx::HighLightEx()
{
	CHARFORMAT cf;
	cf.dwMask = CFM_STRIKEOUT|CFM_BOLD|CFM_COLOR;
	cf.dwEffects = CFE_BOLD;
	cf.crTextColor=RGB(0,0,255);
	
	CHARFORMAT precf;
	precf.dwMask = CFM_STRIKEOUT|CFM_BOLD|CFM_COLOR;
	precf.dwEffects = CFE_BOLD;
	precf.crTextColor=RGB(0,0,0);
	CHARRANGE cr;
	
	CHARRANGE  overflag;
	
	CString strAll;
	CString strBeforre;
	CString strAfter;
	
	GetWindowText(strAll);
	int len=strAll.GetLength();
	int id=GetCareIndex();
	
	for (int q=id-1;q>id-20;q--)
	{
		if ((strAll.GetAt(q))>'z'||(strAll.GetAt(q))<'a')
		{
			CString temp;
			temp=strAll.Left(id);
			strBeforre=temp.Right(id-q-1);
			cr.cpMin=q+1;
			break;
		}
	}
	for (int p=id;p<id+20;p++)
	{
		if ((strAll.GetAt(p))>'z'||(strAll.GetAt(p))<'a')
		{
			CString temp;
			temp=strAll.Right(len-id);
			strAfter=temp.Left(p-id);
			cr.cpMax=p;
			break;
		}	
	}
	strBeforre+=strAfter;

	if (CanFind(strBeforre))
	{
		SetSel(cr);
		SetSelectionCharFormat(cf);
		overflag.cpMax=id;
		overflag.cpMin=id;
		SetSel(overflag);
		SetSelectionCharFormat(precf);
			
	}
	else
	{
		SetSel(cr);
		SetSelectionCharFormat(precf);
		overflag.cpMax=id;
		overflag.cpMin=id;
		SetSel(overflag);
	}		
}

int CRichEditEx::GetCareIndex()
{
	CPoint pt=GetCaretPos();
	for (int n=GetTextLength();n>=0;n--)
	{
		if (GetCharPos(n)==pt)
		{
			return n;
		}
	}
	return -1;
}

BOOL CRichEditEx::CanFind(CString str)
{
	for (int i=0;i<=7;i++)
	{
		if (m_aryString.GetAt(i)==str)
		{
			return TRUE;
		}	
	}
	return FALSE;
}
/


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值