更改 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,您可以使用 SelectionStart、SelectionLength 和 SelectionColor 属性来完成此操作。它运作得很好。
有关这些属性的信息,请查看此页面 。
您可以通过将 SelectionStart 属性设置为当前长度来了解 RichTextBox 文本的长度并为其着色,获取要附加的字符串的长度,设置 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.
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.
Something like that. That's how I remember it working.
我只是在我正在编写的程序中这样做。我正在做类似@itsmatt 的事情,但我感觉更简单一些。您只需设置
Selectioncolor
,从那时起,RichTextBox
就将是该颜色,直到您将其更改为其他颜色。如果您正在测试每一行,这似乎效果很好并且很容易。I was just doing this in a program I was writing. I was doing something like @itsmatt but I feel a bit simpler. You are able to just set the
Selectioncolor
and from that point on theRichTextBox
will be that color until you change it to something else. If you are testing every line this seems to work out well and is easy.