Coloring part of text in richTextBox - c#

So i am currently writing a small IRC bot for Twitch, and i am doing it with WPF, and i would like to color only username in the text line i add to richTextBox. I tryed with simple Foreground coloring but it colors me everytime everything.
My current code:
if (e.ChatMessage.ColorHex.StartsWith("#"))
{
richTextBox.Foreground = ChatUtils.convertHexToBrush(e.ChatMessage.ColorHex);
}
richTextBox.AppendText(String.Format("[{0}] <{1}>: {2}",
DateTime.Now.ToString("HH:mm:ss"),
e.ChatMessage.DisplayName, e.ChatMessage.Message) + "\n");
richTextBox.ScrollToEnd();
So how would i color only the parameter {1} which is e.ChatMessage.DisplayName?

Try like this-
TextRange tr = new TextRange(rtb.Document.ContentEnd,­ rtb.Document.ContentEnd);
tr.Text = e.ChatMessage.DisplayName;
tr.ApplyPropertyValue(TextElement.­ForegroundProperty, Brushes.Red);
See if this helps.

Related

Automatic highlighting a part of the text in a TextBox or RichTextBox

Is it possible to highlight a part of a text without selecting this part of the text preferably with a different color in Textbox or Rich TextBox? In fact, I mean, a part of the text is highlighted by another color differing from the color assigned for text selection. To clarify, I have attached an image showing this behavior. (The image is from a website, not WPF).
The bold and dark green part is a text which is just highlighted, and the gray region is a selected part.
Using the RichTextBox element allows for more styling options which, to my knowledge, aren't available for the regular TextBox element.
Here is an approach that I have created:
// Generate example content
FlowDocument doc = new FlowDocument();
Run runStart = new Run("This is an example of ");
Run runHighlight = new Run("text highlighting in WPF");
Run runEnd = new Run(" using the RichTextBox element.");
// Apply highlight style
runHighlight.FontWeight = FontWeights.Bold;
runHighlight.Background = Brushes.LightGreen;
// Create paragraph
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(runStart);
paragraph.Inlines.Add(runHighlight);
paragraph.Inlines.Add(runEnd);
// Add the paragraph to the FlowDocument
doc.Blocks.Add(paragraph);
// Apply to RichTextBox
YourRichTextBoxHere.Document = doc;
View Screenshot
I found this article to be helpful.
Highlight Searched Text in WPF ListView
While the article is about highlighting searched text in a ListView, I have easily adapted it in my own code to work with pretty much any control.
Starting with the control you pass in, it will recursively look for TextBlocks and will find the text you want, extract it as an inline, and will change it's Background / Foreground properties.
You can easily adapt the code to be a behavior if your want.
Here is an example:
private void HighlightText(object controlToHighlight, string textToHighlight)
{
if (controlToHighlight == null) return;
if (controlToHighlight is TextBlock tb)
{
var regex = new Regex("(" + textToHighlight + ")", RegexOptions.IgnoreCase);
if (textToHighlight.Length == 0)
{
var str = tb.Text;
tb.Inlines.Clear();
tb.Inlines.Add(str);
return;
}
var substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
var run = new Run(item)
{
Background = (SolidColorBrush) new BrushConverter().ConvertFrom("#FFFFF45E")
};
tb.Inlines.Add(run);
}
else
{
tb.Inlines.Add(item);
}
}
}
else
{
if (!(controlToHighlight is DependencyObject dependencyObject)) return;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
HighlightText(VisualTreeHelper.GetChild(dependencyObject, i), textToHighlight);
}
}
}
I hope this is helpful!

How to change part of text color at RichTextBox [duplicate]

This question already has answers here:
Change color and font for some part of text in WPF C#
(5 answers)
Closed 2 years ago.
Good day!
I try to change part of text to red color.
So, i try to use TextBox, but it not works.
So, i read, that RichTextBox can do that:i use this question
But i do not know how to append colored text?
TextRange rangeOfText1 = new TextRange(tbScriptCode.Document.ContentEnd, tbScriptCode.Document.ContentEnd);
rangeOfText1.Text = "Text1 ";
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
Ok, i get TextRange, but how to append it to RichTextBox?
Can you tell me how to make some part of text to red color?
Thank you!
Starting with your example:
TextRange rangeOfText2 = new TextRange(tbScriptCode.Document.ContentEnd,
tbScriptCode.Document.ContentEnd);
rangeOfText2.Text = "RED !";
rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty,Brushes.Red);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
works for me.
Ok, i get TextRange, but how to append it to RichTextBox?
It has already been added with
new TextRange(tbScriptCode.Document.ContentEnd, tbScriptCode.Document.ContentEnd);
What you also can do (I used this myself lately):
var fd = new FlowDocument();
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(new Run("normal text and this is in "));
paragraph.Inlines.Add(new Run("red") { Foreground = Brushes.Red });
paragraph.Inlines.Add(new Run(" and this is blue.") { Foreground = Brushes.Blue });
fd.Blocks.Add(paragraph);
tbScriptCode.Document = fd;

Bold Part of TextBox/RichTextBox in C# Code

There are many examples of how to format the text in a TextBox via xaml code, but I am trying to figure out how to change the code in my .cs file.
//TextBox tb initialized in .xaml code
tb.Text = "<bold>Bold</bold> and normal and <italic>Italic</italic>";
is along the lines of what I am looking for. Is this possible?
The end result would look like:
Bold and normal and Italic
You can do that for RichTextBox by adding Inlines like this:
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(new Bold(new Run("Bold")));
paragraph.Inlines.Add(new Run(" and normal"));
paragraph.Inlines.Add(new Italic(new Run(" and Italic")));
richTextBox.Document = new FlowDocument(paragraph);
If you decide to use TextBlock you can use the following:
this.myTextBlock.Inlines.Add(new Bold(new Run("Bold")));
this.myTextBlock.Inlines.Add(" and normal and ");
this.myTextBlock.Inlines.Add(new Italic(new Run("italic")));
Otherwise, if you have to use TextBox you can only apply style to whole text, for example using myTextBox.FontWeight.

How to change highlight colour of a portion of a text in rich text box?

I am new to WPF's RichTextBox. I would like to know how to highlight text on a line with a specific colour.
Let's say I have a rich text box with a yellow background and assign to it a flow document.
richTextBox.Background = Brushes.LightYellow;
var mcFlowDoc = new FlowDocument();
var para = new Paragraph();
para.Inlines.Add(new Run("This is the first line.\n"));
para.Inlines.Add(new Run("This is the second line.\n"));
para.Inlines.Add(new Run("This is the third line."));
mcFlowDoc.Blocks.Add(para);
richTextBox.Document = mcFlowDoc;
What would I have to do next to change the third line's highlight colour to red? I am not talking about selection highlight colour, but normal text highligting (like in WordPad)
If there is a solution, I would like it in C# code, I want to stay away from XAML editing.
Run run = new Run("Red is the third line.\n");
// run.Foreground = Brushes.Red;
run.Background = Brushes.Red;
para.Inlines.Add(run);

How to make a part of Stringbuilder content bold?

StringBuilder sb = new StringBuilder();
sb.Append(
string.Format("{0} |{1} ", Name, Value)
);
Display.Text = sb.ToString(); // Display is a WP7 TextBlock control
I want to make "Name" as bold. Is it possible to do that ?
ChrisF offers the RichTextBox as a solution but its less well known that simple font variation is acheivable with the simple TextBlock:-
myTextBlock.Inlines.Add(new Run() { Text = "Hello " });
myTextBlock.Inlines.Add(new Run() { Text = "World", FontWeight= FontWeights.Bold });
A StringBuilder only contains character data, not formatting. You can't, basically. Unless you are actually generating html or rtf etc.
In the same way that notepad.exe doesn't have bold/italics/etc.
I'm not a WP7 expert, but maybe there is a different control you can use here, more aimed at formatted text.
You'll need to put the text into a RichTextBox and have the name as a separate Run in the Paragraph as in this example from the MSDN:
// Create a Run of plain text and some bold text.
Run myRun1 = new Run();
myRun1.Text = "A RichTextBox with ";
Bold myBold = new Bold();
myBold.Inlines.Add("initial content ");
Run myRun2 = new Run();
myRun2.Text = "in it.";
// Create a paragraph and add the Run and Bold to it.
Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add(myRun1);
myParagraph.Inlines.Add(myBold);
myParagraph.Inlines.Add(myRun2);
// Add the paragraph to the RichTextBox.
MyRTB.Blocks.Add(myParagraph);

Categories

Resources