Color Different Parts of a Richtextbox String

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.

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 :)

Color specific words in RichtextBox

Add an event to your rich box text changed,

  private void Rchtxt_TextChanged(object sender, EventArgs e)
{
this.CheckKeyword("while", Color.Purple, 0);
this.CheckKeyword("if", Color.Green, 0);
}



private void CheckKeyword(string word, Color color, int startIndex)
{
if (this.Rchtxt.Text.Contains(word))
{
int index = -1;
int selectStart = this.Rchtxt.SelectionStart;

while ((index = this.Rchtxt.Text.IndexOf(word, (index + 1))) != -1)
{
this.Rchtxt.Select((index + startIndex), word.Length);
this.Rchtxt.SelectionColor = color;
this.Rchtxt.Select(selectStart, 0);
this.Rchtxt.SelectionColor = Color.Black;
}
}
}

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);
}

How to change the color of a part of a label c#

The Label control doesn't natively support multiple colors, but the RichTextBox control does! And you can set it's properties to look like a label.

For example, to make it look like a label:

private void Form1_Load(object sender, EventArgs e)
{
// Make the RichTextBox look and behave like a Label control
richTextBox1.BorderStyle = BorderStyle.None;
richTextBox1.BackColor = System.Drawing.SystemColors.Control;
richTextBox1.ReadOnly = true;
richTextBox1.Text = "Hipopotamus";

// I added a small, blank Label control to the form which I use to capture the Focus
// from this control, so the user can't see the caret or select/highlight/edit text
richTextBox1.GotFocus += (s, ea) => { lblHidden.Focus(); };
}

Then a method to highlight a search term by setting selection start and length and changing selected colors:

private void HighlightSearchText(string searchText, RichTextBox control)
{
// Make all text black first
control.SelectionStart = 0;
control.SelectionLength = control.Text.Length;
control.SelectionColor = System.Drawing.SystemColors.ControlText;

// Return if search text isn't found
var selStart = control.Text.IndexOf(searchText);
if (selStart < 0 || searchText.Length == 0) return;

// Otherwise, highlight the search text
control.SelectionStart = selStart;
control.SelectionLength = searchText.Length;
control.SelectionColor = Color.Red;
}

For a test and to show usage, I added a txtSearch textbox control to the form and call the method above in the TextChanged event. Run the form, and type into the textbox to see the results:

private void txtSearch_TextChanged(object sender, EventArgs e)
{
HighlightSearchText(txtSearch.Text, richTextBox1);
}


Related Topics



Leave a reply



Submit