richtextbox中如何实现下面这段文字的字体颜色设置?

问:

richtextbox中如何实现下面这段文字的字体颜色设置?


有如下一个string变量:
"abdscderfvgerg [R]rtrgeferf[/R] er [G]ferfer[/G] f [R]edvferfer[/R] vcferfefrfv dscdsdvd dsdscdsdscsd
dsfefef ddsdfdf dfdf

ewdeerfe erferferf
erferfer
"

先要求把它显示在richtextbox中,所有 [R]XXXXX[/R] 的字串必须显示为红色;所有 [G]XXXXX[/G] 的字串必须显示为蓝色;其它文字显示为黑色。

abdscderfvgerg rtrgeferf er ferfer f edvferfer vcferfefrfv dscdsdvd dsdscdsdscsd
dsfefef ddsdfdf dfdf

ewdeerfe erferferf
erferfer


请问如何实现最简单? 谢谢!

答:

//按钮的单击事件
private void button1_Click(object sender, EventArgs e)
{
string mess = this.rhtxt.Text;
rhtxt.SelectAll();
rhtxt.SelectionColor = Color.Black;
selectColor(mess,Color.Red,"[R]","[/R]");//两个字符之间的
selectColor(mess, Color.Blue, "d", "");//单个字符



}
//变换颜色的通用方法
private void selectColor(string mess,Color color,string benginchar,string endchar)
{
int begindex = 0;
int endindex = 0;
int begingrh = 0;
int endrh = 0;
if (endchar.Trim()==string.Empty)
{
endrh=mess.Length;
while (mess.Length != 0)
{

begindex = mess.IndexOf(benginchar);

if (begindex == -1)
{
break;
}
begingrh += begindex;

rhtxt.Select(begingrh,1);
if (rhtxt.SelectionColor==Color.Black)
{
rhtxt.SelectionColor = color;
}


mess = mess.Substring(begindex+1);
begingrh += 1;

}


}
else
{
while (mess.Length != 0)
{

begindex = mess.IndexOf(benginchar) + benginchar.Length;
endindex = mess.IndexOf(endchar);
if (endindex == -1)
{
break;
}
begingrh = begindex + endrh;
endrh += endindex;
rhtxt.Select(begingrh, endrh - begingrh);
rhtxt.SelectionColor = color;

mess = mess.Substring(endindex + endchar.Length);
begingrh += endchar.Length;
endrh += endchar.Length;
}

}


}
根据传入的参数的不同,进行变化颜色和是单个或多个字符串

你可能感兴趣的:(F#)