2015-10-14 81 views
0

配置:格式的文本颜色表格

  • 的Windows 7
  • .NET 3.5
  • 的Visual Studio 2008

摘要:通过发送的话到RTB一个for循环;根据它们的内容对它们进行格式化(绿色显示“OK”,红色显示“失败”)。

代码:

for (int i = 0; i < inputValues.Length; i++) 
{ 
    //checking if the value is OK or not 
    string answer = functionReturningString(inputValues[i], referenceValue); 
    textBox4.Text += answer; //and sending the result string to text box 
} 

现在我只是想选择最后添加字符串,并根据其内容进行格式化。

textBox4.SelectAll(); 
textBox4.Select(textBox4.SelectedText.Length - answer.Length, answer.Length); 

if (answer == "OK") 
{ 
    textBox4.SelectionColor = Color.Green; 
} else { 
    textBox4.SelectionColor = Color.Red; 
} 

textBox4.Refresh();//I want to see every value as soon as added 
textBox4.Text += "\r\n"; //adding space between words 

至于结果,它最终将对rtb中的所有单词使用“SelectionColor”。

问:如何确保先前格式化的单词不会再改变颜色?

更新:建议的解决方案也不起作用。单词将以正确的颜色显示(首先)。然后添加下一个单词并且整个框的颜色改变。

+3

http://stackoverflow.com/questions/2527700/change-color-of-text-within-a-winforms-richtextbox/2531177#2531177 –

+0

@Ivan stoev我需要删除rtb.refresh(),如果我使用你建议的代码? – Avigrail

+0

我不确定,为什么不尝试看看是否需要。 –

回答

1

的顺序应该是这样的(假设你开始与空丰富的文本框):

richTextBox.SelectionColor = some_Color; 
richTextBox.AppendText(some_Text); 

下面是一个例子模仿你所描述的情况(如果我理解正确的话):

using System; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Windows.Forms; 

namespace Tests 
{ 
    static class Program 
    { 
     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      var form = new Form(); 
      var richTextBox = new RichTextBox { Dock = DockStyle.Fill, Parent = form }; 
      var button = new Button { Dock = DockStyle.Bottom, Parent = form, Text = "Test" }; 
      button.Click += (sender, e) => 
      { 
       Color TextColor = Color.Black, OKColor = Color.Green, FailedColor = Color.Red; 
       var questions = Enumerable.Range(1, 20).Select(n => "Question #" + n).ToArray(); 
       var random = new Random(); 
       richTextBox.Clear(); 
       for (int i = 0; i < questions.Length; i++) 
       { 
        richTextBox.SelectionColor = TextColor; 
        richTextBox.AppendText(questions[i] + ":"); 
        bool ok = (random.Next() & 1) != 0; 
        richTextBox.SelectionColor = ok ? OKColor : FailedColor; 
        richTextBox.AppendText(ok ? "OK" : "Failed"); 
        richTextBox.SelectionColor = TextColor; 
        richTextBox.AppendText("\r\n"); 
       } 
      }; 
      Application.Run(form); 
     } 
    } 
} 

产生以下

enter image description here

+0

哇,这工作得很好!我不知道你可以做些事情(好吗?“OK”:“失败”) 非常感谢:) – Avigrail