更改 WinForms RichTextBox 中文本的颜色 [英] Change color of text within a WinForms RichTextBox

查看:32
本文介绍了更改 WinForms RichTextBox 中文本的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 RichTextBox,每次单击表单按钮时我都会向其中写入一个字符串.每个字符串都以字符串Long"或Short"开头,并以换行符结尾.每次我添加一个字符串时,它都会附加到 RichTextBox 的底部.如果每条线以长"开头,我想将每条线着色为红色,如果以短"开头,则将其着色为蓝色.我该怎么做?

I have a RichTextBox that I write a string to every time I click a Form button. Each string begins with the string "Long" or "Short" and ends with a newline. Each time I add a string, it appends to the bottom of the RichTextBox. I'd like to color each line red if it beings with "Long" and blue if it begins with "Short". How can I do this?

推荐答案

当然,您可以使用 SelectionStart、SelectionLength 和 SelectionColor 属性来完成此操作.效果很好.

Sure, so what you can do is use the SelectionStart, SelectionLength and SelectionColor properties to accomplish this. It works quite well.

查看此页面了解信息在这些属性上.

Check out this page for info on these properties.

您可以通过将 SelectionStart 属性设置为当前长度、获取要附加的字符串的长度、设置 SelectionLength 然后根据需要设置 SelectionColor 来了解 RichTextBox 文本的长度并在此过程中为其着色.冲洗并重复添加的每个字符串.

You can know the length of the RichTextBox text and color this as you go by setting the SelectionStart property to the current length, get the Length of the string you are going to append, set the SelectionLength and then set the SelectionColor as appropriate. Rinse and repeat for each string added.

int length = richTextBox.TextLength;  // at end of text
richTextBox.AppendText(mystring);
richTextBox.SelectionStart = length;
richTextBox.SelectionLength = mystring.Length;
richTextBox.SelectionColor = Color.Red;

类似的东西.我记得它就是这样工作的.

Something like that. That's how I remember it working.

这篇关于更改 WinForms RichTextBox 中文本的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆