Selectively coloring text in RichTextBox
Try this:
static void HighlightPhrase(RichTextBox box, string phrase, Color color) {
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; ) {
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
...
private void button1_Click(object sender, EventArgs e) {
richTextBox1.Text = "Aardvarks are strange animals";
HighlightPhrase(richTextBox1, "a", Color.Red);
}
RichTextBox color specific line
You are missing the else condition, also do it for each line within TexBox like below
string text = richTextBox1.Text;
foreach (var line in richTextBox1.Lines)
{
if (line.Contains("#"))
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
else
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Black;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
}
Inserting Colored text into a RichTextBox
Why don't you use a syntax highlighting control for Windows Forms such as the following ones ?
http://scintillanet.codeplex.com/
https://code.google.com/p/alsing/wiki/SyntaxBox
The first one has SQL support, it took me less time than writing this post to get the following result using their demo app.:
RichTextBox text coloring has different behavior when added to the Form constructor
It seems the reason is Control's Handle
has not been created yet. It is created only when you first call to AppendText
. though it shouldn't be a problem(I'll get back if I find why that's a problem).
To fix it, just force the creation of handle. You do this by requesting the Handle
property.
var handle = richTextBox1.Handle;//Force create handle
for (int i = 0; i < words.Length; i++)
{
string word = words[i];
Color color = colors[i];
richTextBox1.SelectionBackColor = color;
richTextBox1.AppendText(word);
richTextBox1.SelectionBackColor = Color.AliceBlue;
richTextBox1.AppendText(" ");
}
Coloring richtextbox based programming
You are aware that String.Contains does not check for words, aren't you?
If you use String.Contains("able"), then indeed you will find the word "able", but you'll also find words like "disabled", "sable" and "IEquatable".
To check for words you'll need a regular expression.
Whenever you need to process sequences of something, LINQ is your friend. Consider to familiarize yourself with the possibilities of LINQ.
Introduction of LINQ
Using Regular expressions and LINQ I could colorize the complete works of shakespeare (over five million characters) in about 5 seconds
// on load form: fill the rich text box with
// the complete works of William Shakespeare
private async void Form1_Load(object sender, EventArgs e)
{
const string completeShakespeare = "http://www.gutenberg.org/cache/epub/100/pg100.txt";
using (var downloader = new HttpClient())
{
this.richTextBox1.Text = await downloader.GetStringAsync (completeShakespeare);
}
}
// on button click: mark all "thee" red
private void button1_Click(object sender, EventArgs e)
{
var stopwatch = Stopwatch.StartNew();
this.Colorize2("thee", Color.Red);
var elapsed = stopwatch.Elapsed;
Debug.WriteLine ("Coloring a text with {0} characters took {1:F3} sec",
this.richTextBox1.Text.Length,
elapsed.TotalSeconds);
}
private void Colorize2(string word, Color color)
{
string regString = String.Format(@"\b{0}\b", word);
// regex: match substring that match word,
// with boundaries to non alphanumeric characters like space and \n \r \t
var regex = new Regex(regString, RegexOptions.IgnoreCase);
var matches = regex.Matches(richTextBox1.Text);
foreach (Match match in matches.Cast<Match>())
{
this.richTextBox1.Select(match.Index, match.Length);
this.richTextBox1.SelectionColor = color;
}
}
How to retain colors of texts in rich text box?
You shouldn't use Parent
property to hide, but Visible
property instead.
If you hide a richtextbox using richTextBox.Visible = false
it keeps its formatting (tested).
EDIT :
as discussed in the comments below, I suggest you to use only one RichTextBox
and store several Rtf
strings in a Dictionary
(or Hashtable
) to mimic the existence of different RichTextBox
'es.
An example of what I mean can be found Here
Coloring certain words in a RichTextBox
im going to answer my question by myself!
Finally i found a great solution for my problem.
I`ve found a great powerfull UserControl on code-projekt
http://www.codeproject.com/Articles/42490/Using-AvalonEdit-WPF-Text-Editor
My way to the finall solution was:
Adding this to my .xml
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
And this
<avalonEdit:TextEditor Visibility="Hidden" x:Name="RTBAuftragNEU" Margin="32,413,243,279" KeyDown="RTBKunde_KeyDown" Panel.ZIndex="1" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Disabled" > </avalonEdit:TextEditor>
Then put this to my class where i need it.
using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsultingControls.highlight.xshd"))
{
using (XmlTextReader reader = new XmlTextReader(s))
{
RTBAuftragNEU.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
}
}
Dont forget to create the XSHD file for the Syntax, you will find a complete tutorial on the codeproject site.
greetings,
fridolin
Change color and font for some part of text in WPF C#
If you just want to do some quick coloring, the simplest solution may be to use the end of the RTB content as a Range and apply formatting to it. For example:
TextRange rangeOfText1 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText1.Text = "Text1 ";
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
TextRange rangeOfWord = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfWord.Text = "word ";
rangeOfWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
rangeOfWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);
TextRange rangeOfText2 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText2.Text = "Text2 ";
rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
If you are looking for a more advanced solution, I suggest reading this Microsoft Doc about Flow Document, as it gives you a great flexibility in formatting your text.
Related Topics
Accessing a Property of Derived Class from the Base Class in C#
When Is Using the C# Ref Keyword Ever a Good Idea
Internal .Net Framework Data Provider Error 1025
What Does "Displayclass" Name Mean When Calling Lambda
How to Have a Variable Number of Generic Parameters
Authentication with Old Password No Longer Supported, Use 4.1 Style Passwords
How to Sort Databound Datagridview Column
Wpf Textblock Memory Leak When Using Font
How to Cast a Generic Enum to Int
Google Maps V3 Geocoding Server-Side
Wpf Controls Needed to Build Chess Application
How to Change My New List Without Changing the Original List
Equality Comparison Between Multiple Variables
Why Would Try/Finally Rather Than a "Using" Statement Help Avoid a Race Condition
How to Connect to a Ms Access File (Mdb) Using C#
Sortable Jqgrid Using Linq to MySQL (Dblinq) and Dynamic Linq - Orderby Doesn't Work