RichTextBox color specific line - c#

How can I color a line in the RichTextBox which begins with a #, so like a comment in python. I have this code but it should color only the line where the # is in it. My code colors everything after one # is written:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string text = richTextBox1.Text;
if (richTextBox1.Lines.Contains("#") == true)
{
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);
}
}

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

You have to specify the richTextBox1.SelectionLength. You have to set this to your line length.
Also see: Selectively coloring text in RichTextBox

Related

How can I color in a richTextBox only the result text and not all the text in red?

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (results.Count > 0)
{
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value - 1];
richTextBox1.ScrollToCaret();
richTextBox1.SelectionColor = Color.Red;
}
}
I want that when changing the numericUpDown it will color like highlight only the result :
results[(int)numericUpDown1.Value - 1]
Doing ForeColor is coloring all the text in the richTextBox.
I forgot to mention that before this I have a function that highlight specific text in the richTextBox :
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;
}
else
{
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
results.Add(jx);
}
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
And using it :
string word = textBox1.Text;
string[] test = word.Split(new string[] { ",," }, StringSplitOptions.None);
foreach (string myword in test)
{
HighlightPhrase(richTextBox1, myword, Color.Yellow);
label16.Text = results.Count.ToString();
label16.Visible = true;
if (results.Count > 0)
{
numericUpDown1.Maximum = results.Count;
numericUpDown1.Enabled = true;
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value - 1];
richTextBox1.ScrollToCaret();
}
}
Color color = Color.red;
string result = "Result";
string nonColoredPart = "This is not colored";
string partialResultColored = "<color=#" + ColorUtility.ToHtmlStringRGBA(color) + ">" + result+ "</color>" + nonColoredPart;
And then assign the text to the place that accepts Rich Text.
Whenever you want to change the color / font / indentation / tabs etc of only part of the RichTextBox, first select the part that you want to change, then call one of the Selection... methods of the RichTextBox
RichTextBox richTextbox = ...
int startSelect = ...
int selectionLength = ...
richTextbox.Select(startSelect, selectionLength);
// color the selected part red.
richTextBox.SelectionColor = System.Drawing.Color.Red;
// if desired: change other properties of the selected part
System.Drawing.Font currentFont = richTextBox1.SelectionFont;
richTextBox1.SelectionFont = new Font(
currentFont.FontFamily,
currentFont.Size,
FontStyle.Bold);
Check the Select... properties of class RichTextBox

How do I change the color of a string that I display in a textbox? [duplicate]

How can I paint in red every time I meet the letter "A" 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);
}
Here is a snippet out of my wrapper class to do this job:
private delegate void AddMessageCallback(string message, Color color);
public void AddMessage(string message)
{
Color color = Color.Empty;
string searchedString = message.ToLowerInvariant();
if (searchedString.Contains("failed")
|| searchedString.Contains("error")
|| searchedString.Contains("warning"))
{
color = Color.Red;
}
else if (searchedString.Contains("success"))
{
color = Color.Green;
}
AddMessage(message, color);
}
public void AddMessage(string message, Color color)
{
if (_richTextBox.InvokeRequired)
{
AddMessageCallback cb = new AddMessageCallback(AddMessageInternal);
_richTextBox.BeginInvoke(cb, message, color);
}
else
{
AddMessageInternal(message, color);
}
}
private void AddMessageInternal(string message, Color color)
{
string formattedMessage = String.Format("{0:G} {1}{2}", DateTime.Now, message, Environment.NewLine);
if (color != Color.Empty)
{
_richTextBox.SelectionColor = color;
}
_richTextBox.SelectedText = formattedMessage;
_richTextBox.SelectionStart = _richTextBox.Text.Length;
_richTextBox.ScrollToCaret();
}
Now you can call it with AddMessage("The command failed") to get it automatically highlight in red. Or you can call it with AddMessage("Just a special message", Color.Purple) to define a special color (Helpful e.g. within catch blocks to define a specific color, regardless of the message content)
This won't work while you are typing if that is what you are looking for, but I use this to highlight substrings:
Function Highlight(ByVal Search_Str As Object, ByVal InputTxt As String, ByVal StartTag As String, ByVal EndTag As String) As String
Highlight = Regex.Replace(InputTxt, "(" & Regex.Escape(Search_Str) & ")", StartTag & "$1" & EndTag, RegexOptions.IgnoreCase)
End Function
and call it this way:
Highlight("A", "Color All my A's red", [span class=highlight]', '[/span]')
Where the class 'highlight' has whatever color coding/formatting you want:
.highlight {text-decoration: none;color:black;background:red;}
BTW: you need to change those square brackets to angled ones...they wouldn't come thru when I typed them...
This is the C# code for EJ Brennan's answer:
public string Highlight(object Search_Str, string InputTxt, string StartTag, string EndTag)
{
return Regex.Replace(InputTxt, "(" + Regex.Escape(Search_Str) + ")", StartTag + "$1" + EndTag, RegexOptions.IgnoreCase);
}

Color specific words in RichtextBox

How can I make, that when the user types specific words like 'while' or 'if' in a rich textbox, the words will color purple without any problems? I've tried diffrent codes, but none of them were usable. The codes were like below:
if (richTextBox.Text.Contains("while"))
{
richTextBox.Select(richTextBox.Text.IndexOf("while"), "while".Length);
richTextBox.SelectionColor = Color.Aqua;
}
Also, I want that when the user removes the word or removes a letter from the word, the word will color back to its default color. I'm making a program with a code editor in it.
I am using Visual c#.
Thank you.
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;
}
}
}
This is something that you can do, I would recommend using a regular expression to find all matches of the word in case it occurs many times. Also keep in mind that the string find could be a list of strings out side of a for loop to consider multiple words but this should get you started.
//dont foget to use this at the top of the page
using System.Text.RegularExpressions;
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string find = "while";
if (richTextBox1.Text.Contains(find))
{
var matchString = Regex.Escape(find);
foreach (Match match in Regex.Matches(richTextBox1.Text, matchString))
{
richTextBox1.Select(match.Index, find.Length);
richTextBox1.SelectionColor = Color.Aqua;
richTextBox1.Select(richTextBox1.TextLength, 0);
richTextBox1.SelectionColor = richTextBox1.ForeColor;
};
}
}
You can use richTextBox1_KeyDown event
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
String abc = this.richTextBox1.Text.Split(' ').Last();
if (abc == "while")
{
int stIndex = 0;
stIndex = richTextBox1.Find(abc, stIndex, RichTextBoxFinds.MatchCase);
richTextBox1.Select(stIndex, abc.Length);
richTextBox1.SelectionColor = Color.Aqua;
richTextBox1.Select(richTextBox1.TextLength, 0);
richTextBox1.SelectionColor = richTextBox1.ForeColor;
}
}
}
If instead of a word you want to highlight a regular expression, you can use this:
private void ColorizePattern(string pattern, Color color)
{
int selectStart = this.textBoxSrc.SelectionStart;
foreach (Match match in Regex.Matches(textBoxSrc.Text, pattern))
{
textBoxSrc.Select(match.Index, match.Length);
textBoxSrc.SelectionColor = color;
textBoxSrc.Select(selectStart, 0);
textBoxSrc.SelectionColor = textBoxSrc.ForeColor;
};
}

RichTextBox text color

I created RichTextBox and I add this code:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
//( )
int selectionStart = richTextBox1.SelectionStart;
string helpText = richTextBox1.Text;
int closerPos;
for (int i = 0; i < helpText.Length; i++)
{
if (helpText[i] == '(')
{
selectionStart = richTextBox1.SelectionStart;
closerPos = helpText.Substring(i).IndexOf(')') + i;
helpText = helpText.Substring(i + 1, closerPos - i - 1);
richTextBox1.Text = richTextBox1.Text.Remove(i + 1, closerPos - i - 1);
richTextBox1.Select(i + 1, 0);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText = helpText;
richTextBox1.SelectionColor = Color.Black;
helpText = richTextBox1.Text;
richTextBox1.SelectionStart = selectionStart;
}
}
}
This code should color the text between the ( ).
For example:
"Hi (need to be colored) text (sdadsasd) "
the text between the ( ) need to be colored in red. but only the last text is colored. How can I fix it?
You're only getting the first paranthesis with that if condition.
Try splitting the text like helpText.Split('(');
Then iterate over it and do your logic.
I think you can accomplish this without moving byte by byte. You can try to do it using the IndexOf method.
This is something I was thinking of:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string rbText = richTextBox1.Text;
int position = 0;
int startBrace = rbText.IndexOf('(', position) + 1;
while (startBrace != -1)
{
position = rbText.IndexOf(')', startBrace);
if (position != -1)
{
richTextBox1.Select(startBrace, position - startBrace);
richTextBox1.SelectionColor = Color.Red;
startBrace = rbText.IndexOf('(', position) + 1;
}
else
break;
}
}
Keep in mind that I haven't fully test this code.
I already see a potential issue, helpText is being used as an array when it is only a single-variable string. Try breaking the entirety of helpText down into a char array, then iterating through that to find your brackets.

Formatting first line of RichTextBox with capital letters and bold

If I have a RichTextBox and want output like the first line is a font with capital letters and bold, while the next line on the contrary, what should I do?
output like this:
MY NAME IS
Diana
My address is
China
Hey try this, it works, but you might see the text flicker for a second if the user types really fast, like holding down "Enter" and etc.
private void Form_Load(object sender, EventArgs e)
{
// append the function to the RichTextBox's TextChanged event
MyRichTextBox.TextChanged += Capitalize_Bold_FirstLine;
}
private void Capitalize_Bold_FirstLine(object sender, EventArgs e)
{
RichTextBox box = sender as RichTextBox;
if (box != null && box.Text != "")
{
// get the current selection text of the textbox
int ss = box.SelectionStart;
int sl = box.SelectionLength;
// get the position where the first line ends
int firstLineEnd = box.Text.IndexOf('\n');
if (firstLineEnd < 0)
firstLineEnd = box.Text.Length;
// split the lines
string[] lines = box.Text.Split('\n');
// capitalize the first line
lines[0] = lines[0].ToUpper();
// join them back and set the new text
box.Text = String.Join("\n", lines);
// select the first line and make it bold
box.SelectionStart = 0;
box.SelectionLength = firstLineEnd;
box.SelectionFont = new Font(box.Font, FontStyle.Bold);
// select the rest and make it regular
box.SelectionStart = firstLineEnd;
box.SelectionLength = box.Text.Length - firstLineEnd;
box.SelectionFont = new Font(box.Font, FontStyle.Regular);
// go back to what the user had selected
box.SelectionStart = ss;
box.SelectionLength = sl;
}
}

Categories