如何在richtextbox中使用多种颜色
我使用C#windows窗体,我有richtextbox,我想用红色标记一些文本,一些用绿色,一些用黑色。
怎么办? 附图。
System.Windows.Forms.RichTextBox
有一个名为SelectionColor
Color
类型的属性,它获取或设置当前选择或插入点的文本颜色。 您可以使用此属性使用指定的颜色标记RichTextBox
特定字段。
例
RichTextBox _RichTextBox = new RichTextBox(); //Initialize a new RichTextBox of name _RichTextBox _RichTextBox.Select(0, 8); //Select text within 0 and 8 _RichTextBox.SelectionColor = Color.Red; //Set the selected text color to Red _RichTextBox.Select(8, 16); //Select text within 8 and 16 _RichTextBox.SelectionColor = Color.Green; //Set the selected text color to Green _RichTextBox.Select(0,0); //Select text within 0 and 0
请注意 :您可以通过使用RichTextBox.Find(string str)
来避免计算,如果要在RichTextBox
的Lines
中突出显示文本值,可以通过Object Browser
添加它
例
RichTextBox _RichTextBox = new RichTextBox(); //Initialize a new RichTextBox of name _RichTextBox _RichTextBox.Find("Account 12345, deposit 100$, balance 200$"); //Find the text provided _RichTextBox.SelectionColor = Color.Green; //Set the selected text color to Green
谢谢,
我希望你觉得这有用 :)
我找到了这种扩展方法,使您能够更改字符串的颜色以及插入换行值:
public static void AppendText(this RichTextBox box, string text, Color color, bool AddNewLine = false) { if (AddNewLine) { text += Environment.NewLine; } box.SelectionStart = box.TextLength; box.SelectionLength = 0; box.SelectionColor = color; box.AppendText(text); box.SelectionColor = box.ForeColor; }
您可以使用Run对象在运行时更改颜色
private Run GetForegroundColor(string strInformation, Brush color) { Run noramlRun = new Run(strInformation); noramlRun.Foreground = color; return noramlRun; }
对于更复杂的场景,比如根据需求更改颜色,然后访问blow链接