Displaying coloured text in a RichTextbox

92 Views Asked by At

so i have a string of characters that are typically formatted like this:

" text" where the bold character is red.

i want to display these types of strings in a richtextbox with the bold character being red.

i have the text in a string variable and i have the location of the red character (in the string) in an int variable.

my solution is:

  • get characters before the red character
  • get red character
  • get characters after the red character
  • display characters before the red character
  • display red character (with foreground = Brushes.Red)
  • display characters after the red characters

this is what i've got so far:

https://github.com/icebbyice/rapide/blob/master/rapide/SpreadWindow.xaml.cs

find: "//stackoverflow" (also, seperateOutputs is not completed)

i stopped there because i thought there had to be a more efficient way to do it because i will be changing the content of the rich text box often (up to 1000 content changes / 60 seconds).

so, is there a better way to do this?

1

There are 1 best solutions below

0
On

You could do this:

// getting keywords/functions
string keywords = @"\b(e)\b";
MatchCollection keywordMatches = Regex.Matches(codeRichTextBox.Text, keywords);

// saving the original caret position + forecolor
int originalIndex = codeRichTextBox.SelectionStart;
int originalLength = codeRichTextBox.SelectionLength;
Color originalColor = Color.Black;

// MANDATORY - focuses a label before highlighting (avoids blinking)
menuStrip1.Focus();

// removes any previous highlighting (so modified words won't remain highlighted)
codeRichTextBox.SelectionStart = 0;
codeRichTextBox.SelectionLength = codeRichTextBox.Text.Length;
codeRichTextBox.SelectionColor = originalColor;

// scanning...
foreach (Match m in keywordMatches)
{
    codeRichTextBox.SelectionStart = m.Index;
    codeRichTextBox.SelectionLength = m.Length;
    codeRichTextBox.SelectionFont = new Font(codeRichTextBox.Font, FontStyle.Bold);
}

// restoring the original colors, for further writing
codeRichTextBox.SelectionStart = originalIndex;
codeRichTextBox.SelectionLength = originalLength;
codeRichTextBox.SelectionColor = originalColor;
codeRichTextBox.SelectionFont = new Font(codeRichTextBox.Font, FontStyle.Regular);

// giving back the focus
codeRichTextBox.Focus();

That belongs in the RichTextBox TextChanged Event

If you type e, it will display it Bold. Any other text will be displayed as Font.Regular

If you would like to change the syntax from e, then look at the keywords string

This is all I have for this, I hope it helps you :)