我做了个聊天软件 发消息的框是richtextbox1 显示消息的框为richtextbox2我想将 时间 和 发送人 这行 设置为 蓝色先用richTextBox2.Select(start,length);选择要更改的文本,再用richTextBox2.SelectionColor属性设置颜色这样成功了 可是我再在richtextbox1里输入内容 发送 前面设置的颜色又复原了 只有刚发送的内容的 时间 和 发送人 才显示为蓝色
调试欢乐多
private void button1_Click_1(object sender, EventArgs e)
{
string strChars = richTextBox1.Text;
int iOldLength=0; iOldLength = richTextBox2.Text.Length; richTextBox2.AppendText(Environment.NewLine + strChars); if (strChars == "ni")
{
richTextBox2.Select(iOldLength, richTextBox2.Text.Length);
richTextBox2.SelectionColor = Color.Red;
}
else
{
richTextBox2.Select(iOldLength, richTextBox2.Text.Length);
richTextBox2.SelectionColor = Color.Black;
}
}
}
if (strChars == "ni") 这里你来判断是不是要改变颜色了,
我的例子是传递的字符串是ni时变成红色否则是黑子
+= 的话 会出现LZ所说的情况 顺便给端代码public void Disply(ref RichTextBox rtb, string strInput, Color fontColor)
{
int p1 = rtb.TextLength; //取出未添加时的字符串长度。
rtb.AppendText(strInput + "\n"); //保留每行的所有颜色。 // rtb.Text += strInput + "\n"; //添加时,仅当前行有颜色。
int p2 = strInput.Length; //取出要添加的文本的长度
rtb.Select(p1, p2); //选中要添加的文本
rtb.SelectionColor = fontColor; //设置要添加的文本的字体色
//rtb.Refresh();
}