How to Use Multi Color in 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.

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 use multi color in richtextbox WPF

Use FlowDocumentReader in your RichTextBox. Thus, you can use document classes: List, Paragraph, Section, Table, LineBreak, Figure, Floater and Span, and change their properties:

<FlowDocumentReader x:Name="myDocumentReader" Height="269.4">
<FlowDocument>
<Section Foreground = "Yellow" Background = "Black">
<Paragraph FontSize = "20">
Here are some fun facts about the WPF Documents API!
</Paragraph>
</Section>
<List x:Name="listOfFunFacts"/>
<Paragraph x:Name="paraBodyText"/>
</FlowDocument>
</FlowDocumentReader>

You can also fill and change properties of, here for example, List right in the code:

this.listOfFunFacts.Foreground = Brushes.Brown;
this.listOfFunFacts.FontSize = 14;
this.listOfFunFacts.MarkerStyle = TextMarkerStyle.Circle;
this.listOfFunFacts.ListItems.Add(new ListItem( new Paragraph(new Run("Sample Text"))));

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 color different words in a RichTextBox with different colors?

you should use RichTextBox to color your lines of text, use this snippet.

txtRichTextBox.Select(yourText.IndexOf("portion"), "portion".Length);
txtRichTextBox.SelectionColor = YourColor;
txtRichTextBox.SelectionFont = new Font("Times New Roman",FontStyle.Bold);

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

vb.net - Multicolor RichTextBox

It's not really clear what you're trying to achieve. I'm not sure I understand the bracketed formatting nearly as well as I would an image that you mocked up in Paint. But here goes anyway...

I suspect there are a couple of problems with your existing code. First up is the location of the cursor when you insert new text. What's supposed to come after the first snippet actually gets inserted before it because of where the insertion mark is located. To fix that, you need to move it manually.

You're also assigning a string of text to the Text property at the end of your code, which does not preserve the existing formatting information. I suspect that the simplest thing for you to do is to use the AppendText method, instead.

And finally, I recommend using the simpler overload to create a new font, since the only thing you want to change is the style. The advantage of using this instead is that you don't have to hardcode the name and size of the font in your code, in case you want to change it later.

Try rewriting your code to this instead:

' Insert first snippet of text, with default formatting
RichTextBox1.Text = "This is black "

' Move the insertion point to the end of the line
RichTextBox1.Select(RichTextBox1.TextLength, 0)

'Set the formatting and insert the second snippet of text
RichTextBox1.SelectionFont = New Font(RichTextBox1.Font, FontStyle.Bold)
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.AppendText("[BOLD GREEN]")

' Revert the formatting back to the defaults, and add the third snippet of text
RichTextBox1.SelectionFont = RichTextBox1.Font
RichTextBox1.SelectionColor = RichTextBox1.ForeColor
RichTextBox1.AppendText(" black again")

The result will look like this:

   sample RichTextBox with formatted text

RichTextBox Multi-Line Color (Partial Line Color Only)

The issue is caused by replacing the string in the Text property:

rtb.Text = rtb.Text.TrimEnd('\n');

This line of code causes the entire control to remove all current formatting Per MSDN:

The Text property does not return any information about the formatting applied to the contents of the RichTextBox. To get the rich text formatting (RTF) codes, use the Rtf property. The amount of text that can be entered in the RichTextBox control is limited only by available system memory.

Otherwise, the code can be simplified to just:

Color textColor = Color.Black;
switch (e.Status) {
case Status.Error: textColor = Color.DarkRed; break;
case Status.Warning: textColor = Color.DarkGoldenrod; break;
case Status.Success: textColor = Color.DarkGreen; break;
}
rtb.Select(rtb.TextLength, 0);
rtb.SelectionColor = textColor;
rtb.AppendText($"{e.Message}\n");
rtb.ScrollToCaret();


Related Topics



Leave a reply



Submit