Change Color of Text Within a Winforms Richtextbox

Color different parts of a RichTextBox string

Here is an extension method that overloads the AppendText method with a color parameter:

public static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;

box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
}

And this is how you would use it:

var userid = "USER0001";
var message = "Access denied";
var box = new RichTextBox
{
Dock = DockStyle.Fill,
Font = new Font("Courier New", 10)
};

box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);

new Form {Controls = {box}}.ShowDialog();

Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.

Change color of text within a WinForms RichTextBox

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.

Change current color in a richTextBox?

Basically richTxtBox.FrontColor = Color.Red; will change the color of all text to Red, but you requirement is to change only the color of selected text, for that you need to use, richTextBox1.SelectionColor = Color.Red; which will change the color of only selected text.

You can decide which portion of the text need to be selected by using SelectionStart and SelectionLength. it is purely working on the basics of the index.

The mentioned problem of selecting the typed text in richTextBox1_TextChanged can be avoid by using this snippet

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (richTextBox1.SelectionStart != 0)
{
int length = richTextBox1.Text.Length;
richTextBox1.Select(richTextBox1.SelectionStart - 1, 1);
richTextBox1.SelectionColor = Color.Red ;
richTextBox1.SelectionStart = length;
}
}

Apart from other answers here i have a magic box, which will changes the colors based on text.

enter image description here

And this can be achieved by using the following code:

private void button1_Click(object sender, EventArgs e)
{
int selectionStart = 0;
foreach (var item in richTextBox1.Text.Split(' '))
{
Color rgb = Color.FromName(item);
richTextBox1.SelectionStart = selectionStart;
richTextBox1.SelectionLength = item.Length;
richTextBox1.SelectionColor = rgb;
selectionStart += item.Length + 1;
}

}

How to use multi color in richtextbox

System.Windows.Forms.RichTextBox has got a property of type Color of the name SelectionColor which gets or sets the text color of the current selection or insertion point. You can use this property to mark specific fields in your RichTextBox with the colors you specify.

Example

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

Notice that: You may avoid calculations by using RichTextBox.Find(string str) which can be added through Object Browser if you would like to highlight the text within the Lines in RichTextBox giving it's value

Example

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

Thanks,

I hope you find this helpful :)

How to color different words with different colors in a RichTextBox while a user is writing and raise an event when that colored text is clicked

Given the requirements:

1) A User inserts some text in a RichTextBox Control.

2) If the word entered is part of a pre-defined list of words, that word should change color (so, define a relation between a word and a color).

3) When a mouse Click event is generated on a colored word, an event is raised, to notify which word was clicked.

Possible result (to replicate what's in the visual example):

RicheTextBox write words in Colors

Define a custom EventHandler with custom EventArgs:

public class WordsEventArgs : EventArgs
{
private string m_word;
public WordsEventArgs(string word) { m_word = word; }
public string Word { get { return m_word; } set { m_word = value; } }
}

public delegate void WordsEventHandler(object sender, WordsEventArgs e);
public event WordsEventHandler WordClicked;

protected void OnWordClicked(WordsEventArgs e) => WordClicked?.Invoke(this, e);

Subscribe to the event:

this.WordClicked += new WordsEventHandler(this.Word_Click);

Simple Class for the list of words:

public class ColoredWord
{
public string Word { get; set; }
public Color WordColor { get; set; }
}

public List<ColoredWord> ColoredWords = new List<ColoredWord>();

Fill the list with some words an related color, then bind it to a ListBox, calling the FillColoredWords() method (in other words, handle a collection of objects that relate pieces of text with Color values):

public void FillColoredWords()
{
ColoredWords.Add(new ColoredWord { Word = "SIMPLE", WordColor = Color.Goldenrod });
ColoredWords.Add(new ColoredWord { Word = "COLORED", WordColor = Color.Salmon });
ColoredWords.Add(new ColoredWord { Word = "TEXT", WordColor = Color.DarkCyan });
this.listBox1.DisplayMember = "Word";
this.listBox1.DataSource = ColoredWords;
}

In the KeyPress event, evaluate whether the last entered word is part of the list of words to color:

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int currentPosition = richTextBox1.SelectionStart;

if (e.KeyChar == (char)Keys.Space && currentPosition > 0 && richTextBox1.Text.Length > 1) {
int lastSpacePos = richTextBox1.Text.LastIndexOf((char)Keys.Space, currentPosition - 1);
lastSpacePos = lastSpacePos > -1 ? lastSpacePos + 1 : 0;

string lastWord = richTextBox1.Text.Substring(lastSpacePos, currentPosition - (lastSpacePos));
ColoredWord result = ColoredWords.FirstOrDefault(s => s.Word == lastWord.ToUpper());

richTextBox1.Select(lastSpacePos, currentPosition - lastSpacePos);
if (result != null) {
if (richTextBox1.SelectionColor != result.WordColor) {
richTextBox1.SelectionColor = result.WordColor;
}
}
else {
if (richTextBox1.SelectionColor != richTextBox1.ForeColor) {
richTextBox1.SelectionColor = richTextBox1.ForeColor;
}
}
richTextBox1.SelectionStart = currentPosition;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = richTextBox1.ForeColor;
}
}

In the MouseClick event, verify whether the event is generated on a colored word.

In that case, raise the custom OnWordClicked() event:

private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
{
if (richTextBox1.SelectionColor.ToArgb() != richTextBox1.ForeColor.ToArgb()) {
try {
int wordInit = richTextBox1.Text.LastIndexOf((char)32, richTextBox1.SelectionStart);
wordInit = wordInit > -1 ? wordInit : 0;
int wordEnd = richTextBox1.Text.IndexOf((char)32, richTextBox1.SelectionStart);
string wordClicked = richTextBox1.Text.Substring(wordInit, wordEnd - wordInit) + Environment.NewLine;
OnWordClicked(new WordsEventArgs(wordClicked));
}
catch (Exception) {
//Handle a fast DoubleClick: RTB is a bit dumb.
//Handle a word auto-selection that changes the `.SelectionStart` value
}
}
}

In the custom event, you can append the clicked word to a TextBox (or do whatever else you want to do with it):

private void Word_Click(object sender, WordsEventArgs e)
{
textBox1.AppendText(e.Word);
}

WinForm RichTextBox text color changes too many characters

Your Select() call leaves the SelectionStart property at the start of the appended text instead of end of the text. You could restore it like you did for SelectionLength, but the simpler way to do it is:

    private static void AppendTextColor(RichTextBox box, Color color, string text) {
box.SelectionStart = box.Text.Length; // Optional
var oldcolor = box.SelectionColor;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = oldcolor;
}

Note the // Optional comment, it isn't needed when the user cannot edit the text.

Do beware that you have a very serious fire-hose problem in your code. You are calling Invoke() at a very high rate, liable to cause the UI thread to start burning 100% core when the box starts filling up. Easy to tell when that happens, you can't see updates anymore and your program stops responding to input. Buffering in the DataReceived event handler is required, using ReadLine() instead of ReadExisting() is usually the simple way to get there. And use BeginInvoke() instead, Invoke() is very likely to cause the SerialPort.Close() call to deadlock.



Related Topics



Leave a reply



Submit