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

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

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

C# Textbox, how to set a specific color for a specific word

I didn't used C# WinForms for a while, but as I remember you have object aka RichTextBox which allows you to do more things (and use more then one style for your text).

You will find more info in this link:
RichTextBox.SelectedText

Good luck

How to change color for specific string in richTextBox

inside richTextBox_TextChanged check the full line of text when comparing

string str = "red string";
for(int i=0; i<richTextBox1.Lines.Length; i++)
{
string text = richTextBox1.Lines[i];
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), text.Length);
if(text ==str)
{
richTextBox1.SelectionColor = Color.Red;
}else
{
richTextBox1.SelectionColor = Color.Black;
}
}

for multiple colors, I would use dictionary

var dictionary = new Dictionary<string, System.Drawing.Color>();
dictionary.Add("red color", System.Drawing.Color.Red);
dictionary.Add("Blue color", System.Drawing.Color.Blue);
//as above example you can use for loop and get each line of rich textbox
string linefromTextBox = "Blue color";
//then check that line contain of of text in the dictionaly
if (dictionary.ContainsKey(linefromTextBox))
{
// if key found then you can get the color as below
// asign this as SelectionColor
//before that you need to Select the line from rich text box as above example
var color = dictionary[linefromTextBox];
}

RichTextBox remove color from deleted 'keywords'

You can reset the color of complete text to the default color (black in this case) and then run your usual keyword coloring to apply the colors again.

    private void Rchtxt_TextChanged(object sender, EventArgs e)
{
this.CheckKeyword(Rchtxt.Text, Color.Black, 0);
this.CheckKeyword("and", Color.Red, 0);
this.CheckKeyword("or", Color.Red, 0);
}

Click and recognize part of text in textbox vb.net

Try this:

Private Sub TextBox1_Click(sender As Object, e As EventArgs) Handles TextBox1.Click
Dim SplitText As String() = TextBox1.Text.Split(CChar("<"), ">")
Dim SelectedText As String = GetSelectedText()
Dim Options As New List(Of String)

If Not SelectedText = "" Then
For i = 0 To SplitText.Length - 1
If IsNumeric(SplitText(i)) Then
Options.Add("<" & SplitText(i) & ">")
End If
Next
For i = 0 To Options.Count - 1
If SelectedText = Options(i) Then
'Put your code here if it is the current option in the loop equals the selected option.
'I added a messagebox just so you can see the current option.
MessageBox.Show("You selected option: " & Options(i))
End If
Next
End If
End Sub

Private Function GetSelectedText()
Dim CursorPosition As Integer = TextBox1.SelectionStart
Dim SelectedNumber As String = ""
Dim NumberLength As Integer = 0

If CursorPosition = 0 Or CursorPosition = TextBox1.Text.Length Then
Return ""
End If
Do Until Mid(TextBox1.Text, CursorPosition - NumberLength, 1) = "<"
NumberLength += 1
Loop
SelectedNumber = Mid(TextBox1.Text, CursorPosition - NumberLength, NumberLength + 1)
NumberLength = 0
CursorPosition += 1
Do Until Mid(TextBox1.Text, CursorPosition + NumberLength, 1) = ">"
NumberLength += 1
Loop
SelectedNumber &= Mid(TextBox1.Text, CursorPosition, NumberLength + 1)

If IsNumeric(SelectedNumber.Remove(0, 1).Remove(SelectedNumber.Length - 2, 1)) Then
Return SelectedNumber
Else
Return ""
End If
End Function

I put this inside of the textbox click event, and it works. I did not try putting the code in any other events. I assume that the textbox is named: TextBox1.



Related Topics



Leave a reply



Submit