更改 WinForms RichTextBox 中文本的颜色

发布于 2024-08-26 13:24:16 字数 158 浏览 10 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彩扇题诗 2024-09-02 13:24:16

当然,您可以使用 SelectionStart、SelectionLength 和 SelectionColor 属性来完成此操作。它运作得很好。

有关这些属性的信息,请查看此页面

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

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

类似的事情。我记得它就是这样工作的。

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.

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.

凉城已无爱 2024-09-02 13:24:16

我只是在我正在编写的程序中这样做。我正在做类似@itsmatt 的事情,但我感觉更简单一些。您只需设置 Selectioncolor,从那时起,RichTextBox 就将是该颜色,直到您将其更改为其他颜色。如果您正在测试每一行,这似乎效果很好并且很容易。

if(myString == "Long") 
{ 
  richTextBox.SelectionColor = Color.Red; 
}
else
{
  richTextBox.SelectionColor = Color.Green
}
richTextBox.AppendText(myString);

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 the RichTextBox 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.

if(myString == "Long") 
{ 
  richTextBox.SelectionColor = Color.Red; 
}
else
{
  richTextBox.SelectionColor = Color.Green
}
richTextBox.AppendText(myString);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文