c# wpf richtextbox selection - c#

I have a RichTextBox with for example this piece of text:
Hi, my name is {name}!
When I put my cursor between the brackets I want my richtextbox to select the entire word between brackets and also the brackets.
so when I do this: ('|'is the cursor)
Hi, my name is {n|ame}!
I want to select '{name}'
How can I do this?

I have made this to extend the selection in a WPF RichTextBox. I'm new to WPF so I don't know if it's the best way to do it.
private TextRange ExtendSelection(LogicalDirection direction)
{
TextRange tr = new TextRange(CaretPosition, CaretPosition.GetInsertionPosition(direction));
bool found = false;
while (!found)
{
if (tr == null)
{
break;
}
else
{
// If we are not at the end of the document (or at the beginning)
TextPointer next = null;
if (LogicalDirection.Forward.CompareTo(direction) == 0 && tr.End.CompareTo(Document.ContentEnd) == -1)
{
next = tr.End.GetNextInsertionPosition(direction);
}
else if (LogicalDirection.Backward.CompareTo(direction) == 0 && tr.Start.CompareTo(Document.ContentStart) == 1)
{
next = tr.Start.GetNextInsertionPosition(direction);
}
// Be careful with boundaries!
if (next != null)
{
TextRange trNext = new TextRange(CaretPosition, next);
char[] text = trNext.Text.ToCharArray();
for (int i = 0; i < text.Length; i++)
{
if (Char.IsWhiteSpace(text[i]) || Char.IsSeparator(text[i]))
{
found = true;
break;
}
}
if (!found)
{
tr = trNext;
}
}
else
{
break;
}
}
}
return tr;
}
private void MyRichTextBox_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TextRange left = ExtendSelection(LogicalDirection.Backward);
TextRange right = ExtendSelection(LogicalDirection.Forward);
if (!left.IsEmpty && !right.IsEmpty)
{
Selection.Select(left.Start, right.End);
Console.WriteLine("Highlight: '" + Selection.Text + "'");
}
}

I write something you can work on (the code below only works with a single line RTB):
private void richTextBox1_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
TextPointer oldpointer = richTextBox1.CaretPosition; //current caret position
int startposition = richTextBox1.Document.ContentStart.GetOffsetToPosition(richTextBox1.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward));
if (startposition > 2)
{ //get RTB text
richTextBox1.SelectAll();
string wholetext = richTextBox1.Selection.Text;
//reset the caret back
richTextBox1.CaretPosition = oldpointer;
//split text by the caret
string starthalf = wholetext.Substring(0, startposition - 2);
string endhalf = wholetext.Remove(0, startposition - 2);
//get position of "{" and "}"
int seleStart = starthalf.LastIndexOf('{');
int seleEnd = endhalf.IndexOf('}') < 0 ? -1 : endhalf.IndexOf('}') + starthalf.Length + 1;
//select the pattern
if (seleStart >= 0 && seleEnd > 0)
{
richTextBox1.Selection.Select(richTextBox1.Document.ContentStart.GetPositionAtOffset(seleStart + 2), richTextBox1.Document.ContentStart.GetPositionAtOffset(seleEnd + 2));
}
}
}

Related

Change back color of specific text in richtextbox wpf

I am working on function, that will change back color of tags in text of RichTextBox (blah blah blah < i>This will be changed< /i> blah blah blah). I tried to make some code, but it is highlighting correctly only first tag. The second tag will be highlited a few chars before. Please, how could I get this work?
Actual state - Function colorize correctly only first tag, others are colored characters before.
State I want - Have colored only tags and it's content in RichTextBox.
Problem part:
TextPointer text = txbPlainText.Document.ContentStart;
while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
{
text = text.GetNextContextPosition(LogicalDirection.Forward);
}
TextPointer start = text.GetPositionAtOffset(tagStartIndex);
TextPointer end = text.GetPositionAtOffset(i + tagBuilder.Length);
TextRange textRange = new TextRange(start, end);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Color.FromRgb(220, 204, 163)));
How it looks like:
Image with problem
This is whole function:
private void ColorizeTags()
{
string tagString = string.Empty;
int tagStartIndex = 0;
char[] txbChars = GetTxbText().ToCharArray();
for (int i = 0; i < txbChars.Count(); i++)
{
char actualChar = txbChars[i];
if (actualChar == '<' && txbChars[i + 1] != '/')
{
StringBuilder tagBuilder = new StringBuilder();
foreach (string tag in TagList)
{
for (int x = i; x < (i + tag.Length); x++)
{
if (x > txbChars.Count())
{
break;
}
tagBuilder.Append(txbChars[x]);
}
if (tagBuilder.ToString() == tag)
{
tagString = tagBuilder.ToString();
tagStartIndex = i;
break;
}
}
}
else if (actualChar == '<' && txbChars[i + 1] == '/')
{
if (string.IsNullOrWhiteSpace(tagString))
{
continue;
}
string endTag = tagString.Insert(tagString.IndexOf('<') + 1, "/");
StringBuilder tagBuilder = new StringBuilder();
for (int c = i; c < (i + endTag.Length); c++)
{
tagBuilder.Append(txbChars[c]);
}
if (tagBuilder.ToString() == endTag)
{
TextPointer text = txbPlainText.Document.ContentStart;
while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
{
text = text.GetNextContextPosition(LogicalDirection.Forward);
}
TextPointer start = text.GetPositionAtOffset(tagStartIndex);
TextPointer end = text.GetPositionAtOffset(i + tagBuilder.Length);
TextRange textRange = new TextRange(start, end);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Color.FromRgb(220, 204, 163)));
tagString = string.Empty;
continue;
}
}
}
}
private string GetTxbText()
{
return new TextRange(txbPlainText.Document.ContentStart, txbPlainText.Document.ContentEnd).Text;
}
I searched and found the problem. The thing is when I was getting the position offset of the start and the end, value of the current textpointer has changed.
And second problem was, that my TextPointer text ignored whitespaces, solution below.
Solution: Don't get position offset straightly.
Before:
...
TextPointer text = txbPlainText.Document.ContentStart;
while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
{
text = text.GetNextContextPosition(LogicalDirection.Forward);
}
TextPointer start = text.GetPositionAtOffset(tagStartIndex);
TextPointer end = text.GetPositionAtOffset(i + tagBuilder.Length);
...
After:
...
TextPointer text = txbPlainText.Document.ContentStart;
TextPointer start = GetTextPointAt(text, tagStartIndex);
TextPointer end = GetTextPointAt(text, endIndex);
...
private static TextPointer GetTextPointAt(TextPointer from, int pos)
{
TextPointer ret = from;
int i = 0;
while ((i < pos) && (ret != null))
{
if ((ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text) || (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None))
i++;
if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null)
return ret;
ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward);
}
return ret;
}
Source of answer

Can I browse text backwards for a String in Visual C#?

I have a Search function with them I can Search a string inside my richtextbox from the beginning of the text to the end. When I found the last accordance it start from begin.
Here the code:
#region Search
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
start = 0;
end = 0;
}
//Searchfield
private void toolStripTextBoxSearch_Click(object sender, EventArgs e)
{
}//end TextBoxSearch
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
if (searchStart >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}//end FindMyText
private void buttonSearch_left_Click(object sender, EventArgs e)
{
}
private void buttonSearch_right_Click(object sender, EventArgs e)
{
int startindex = 0;
if (txtSearch.Text.Length > 0)
{
startindex = FindMyText(txtSearch.Text, start, richTextBox.Text.Length);
}
// If string was not found report it
if (startindex < 0 )
{
if (stringfoundflag==1)
{
startindex = FindMyText(txtSearch.Text, 0, richTextBox.Text.Length); //Start at Pos. 0
}
else
{
MessageBox.Show("Not found in Textfield", "Search", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}//end if
if (startindex >= 0)
{
stringfoundflag = 1;
// Set the highlight color as red
//richTextBox.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
richTextBox.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
// Reset the richtextbox when user changes the search string
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
private void txtSearch_Enter(object sender, EventArgs e)
{
if (txtSearch.Text == "Search")
{
txtSearch.Text = "";
}
}
private void txtSearch_Leave(object sender, EventArgs e)
{
if (txtSearch.Text == "")
{
txtSearch.Text = "Search";
}
}
#endregion
I have two button one search right and one left, the right works like the description at the start.
Question:
Can I reverse the searchfunction from button right to left with my solution, or must I change the whole search function?
Example: Start at first accordance and jump than to the last accordance and then next-to-last and so on.
I found a solution for my problem.
Code:
public int FindMyTextleft(string txtToSearch, int searchStart, int searchEnd)
{
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
if (searchStart >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.Reverse);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}//end FindMyTextleft
return retVal;
}//end FindMyText
private void buttonSearch_left_Click(object sender, EventArgs e)
{
int startindex = 0;
if (txtSearch.Text.Length > 0 & stringfoundflag == 1)
{
startindex = FindMyTextleft(txtSearch.Text, startindex, end);
}
else if (txtSearch.Text.Length > 0)
{
startindex = FindMyTextleft(txtSearch.Text, start, richTextBox.Text.Length);
}
// If string was not found report it
if (startindex < 0)
{
if (stringfoundflag == 1)
{
startindex = FindMyTextleft(txtSearch.Text, 0, richTextBox.Text.Length); //Start at Pos. 0
}
else
{
MessageBox.Show("Not found in Textfield", "Search", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}//end if
if (startindex >= 0)
{
stringfoundflag = 1;
// Set the highlight color as red
//richTextBox.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
richTextBox.Select(startindex, endindex);
// mark the start position after the position of
// last search string
end = startindex;
}
}//buttonSearch_left_Click

How to display 2nd page on printpreview

The Print Preview controller shows the first page not the 2n or 3rd.. pages.
Show_Page() method displays the all pages without problem in a list view.
The method that I use for changing the pages print preview controller is as below:
What should I change or add for displaying next and previous pages ?
private void nxtBtn_Click(object sender, EventArgs e)
{
if (PrevIndex < PgCount)
++PrevIndex;
if (PrevIndex == PgCount - 1)
nxtBtn.Enabled = false;
prvBtn.Enabled = true;
ppd.PrintPreviewControl.InvalidatePreview();
fName = GetFName();
if (PublicVariables.PrintData == 2)
Show_Page();
else
{
pd.DocumentName = fName;
ppd.Document = pd;
ppc.Document = pd;
ppc.Update();
}
label2.Text = (PrevIndex + 1).ToString();
}
private void ShowPage()
{
streamToRead = new StreamReader(fName, Encoding.UTF8);
string line;
int LineNbr = 0;
li.Items.Clear();
LineNbr = File.ReadAllLines(fName).Length;
li.View = View.Details;
int counter = 0;
ListViewItem Lvi = new ListViewItem();
char sep='|';
int ctr_limit=0;
if (PublicVariables.Grup_It == 0)
ctr_limit = 9;
else
ctr_limit = 7;
string[] tmp1 = new string[ctr_limit];
while (counter < LineNbr && (line = streamToRead.ReadLine()) != null)
{
if (PublicVariables.PrintData == 2 && counter < 3)
goto NextLine;
string[] tmp = line.Split(sep);
for (int i = 0; i < ctr_limit; ++i)
{
if (PublicVariables.Grup_It > 0)
tmp1[i] = tmp[i + 1];
else
tmp1[i] = tmp[i];
}
Lvi = new ListViewItem(tmp1);
li.Items.Add(Lvi);
NextLine:
++counter;
}
streamToRead.Close();
}
private void nxtBtn_Click(object sender, EventArgs e)
{
if (PrevIndex < PgCount)
++PrevIndex;
if (PrevIndex == PgCount - 1)
nxtBtn.Enabled = false;
prvBtn.Enabled = true;
ppd.PrintPreviewControl.InvalidatePreview();
fName = GetFName();
if (PublicVariables.PrintData == 2)
Show_Page();
else
{
pd.DocumentName = fName;
ppd.Document = pd;
ppc.Document = pd;
ppc.InvalidatePreview();
}
label2.Text = (PrevIndex + 1).ToString();
}
Instead of ppc.Update() I have to write ppc.InvalidatePreview();
That permits to show the next page.

Searching string in richtextbox

This is my code on finding text in my richtextbox and highlighting it:
int start = 0;
int indexOfSearchText = 0;
private void button1_Click(object sender, EventArgs e)
{
int startindex = 0;
if (textBox1.Text.Length > 0)
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
richTextBox1.SelectionBackColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = textBox1.Text.Length;
// Highlight the search string
richTextBox1.Select(startindex, endindex);
richTextBox1.ScrollToCaret();
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
else
{
MessageBox.Show("0 occurence in richtextbox");
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
richTextBox1.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox1.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
}
}
The problem is, when it reaches the end of the richtextBox1, it did not restart at the beginning again! I want to loop it again to the start after reaching the end of the richtextBox1.text.
What about this?
if (textBox1.Text.Length > 0)
{
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
if(startindex == -1 && start > 0) // Not found string and not searching from beginning
{
// Wrap search
int oldStart = start;
start = 0;
startindex = FindMyText(textBox1.Text.Trim(), start, oldStart);
}
}
The below code is useful for searching a text in richtextbox and highlighting the text in round direction.I was using textbox in richtextbox.i,m entering the search text in textbox and pressing enter button for find next.Initially i,m declaring two values as 0 for start and indexOfSearchText.
int start = 0;
int indexOfSearchText = 0;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
int startindex = 0;
if (textBox1.Text.Length > 0)
{
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
if (startindex == -1 && start >= 0) // Not found string and not searching from beginning
{
// Wrap search
// int oldStart = start;
start = 0;
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
}
}
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
richTextBox1.Select(startindex, textBox1.TextLength);
richTextBox1.SelectionBackColor = Color.Yellow;
// richTextBox1.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = textBox1.Text.Length;
// Highlight the search string
richTextBox1.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
richTextBox1.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox1.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
else
{
start = 0;
indexOfSearchText = 0;
//return indexOfSearchText;
}
}
}
return retVal;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
string temp = richTextBox1.Text;
richTextBox1.Text = string.Empty;
richTextBox1.Text = temp;
richTextBox1.SelectionBackColor = Color.White;
}

Highlight all searched words

In my RichtextBox, if I have written as below.
This is my pen,
his pen is beautiful.
Now I search word "is" then
output would be as below.
All "is" should be highlighted.
What about:
static class Utility {
public static void HighlightText(this RichTextBox myRtb, string word, Color color) {
if (word == string.Empty)
return;
int s_start = myRtb.SelectionStart, startIndex = 0, index;
while((index = myRtb.Text.IndexOf(word, startIndex)) != -1) {
myRtb.Select(index, word.Length);
myRtb.SelectionColor = color;
startIndex = index + word.Length;
}
myRtb.SelectionStart = s_start;
myRtb.SelectionLength = 0;
myRtb.SelectionColor = Color.Black;
}
}
Looks like this would do it.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=146
int start = 0;
int indexOfSearchText = 0;
private void btnFind_Click(object sender, EventArgs e)
{
int startindex = 0;
if(txtSearch.Text.Length > 0)
startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
rtb.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
rtb.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
rtb.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >=0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}
// Reset the richtextbox when user changes the search string
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
This will show all the searched criteria at the same time.
Using: 1 Textbox (to enter the text to search for) and 1 Button (to Run the Search).
Enter your search criteria inside the textbox and press search button.
// On Search Button Click: RichTextBox ("rtb") will display all the words inside the document
private void btn_Search_Click(object sender, EventArgs e)
{
try
{
if (rtb.Text != string.Empty)
{// if the ritchtextbox is not empty; highlight the search criteria
int index = 0;
String temp = rtb.Text;
rtb.Text = "";
rtb.Text = temp;
while (index < rtb.Text.LastIndexOf(txt_Search.Text))
{
rtb.Find(txt_Search.Text, index, rtb.TextLength, RichTextBoxFinds.None);
rtb.SelectionBackColor = Color.Yellow;
index = rtb.Text.IndexOf(txt_Search.Text, index) + 1;
rtb.Select();
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); }
}
}
}
If you only want to match the whole word you can use this, note that this ignores case and also the |s\b means that plurals get highlighted e.g. Cat matches cats but not caterpiller :
public static void HighlightText(RichTextBox myRtb, string word, Color color)
{
if (word == string.Empty)
return;
var reg = new Regex(#"\b" + word + #"(\b|s\b)",RegexOptions.IgnoreCase);
foreach (Match match in reg.Matches(myRtb.Text))
{
myRtb.Select(match.Index, match.Length);
myRtb.SelectionColor = color;
}
myRtb.SelectionLength = 0;
myRtb.SelectionColor = Color.Black;
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
for (int i = 0; i < richTextBox1.TextLength; i++)
{
richTextBox1.Find(textBox1.Text, i, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Red;
}
}
else
{
for (int i = 0; i < richTextBox1.TextLength; i++)
{
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
}
}
}[lets make it!][1]
I would do it like that because all the other answers highlight the text, but doesnt change it back after you searched again.
Use the RichText Find Method to find the starting index for the searching word.
public int FindMyText(string searchText, int searchStart, int searchEnd)
{
int returnValue = -1;
if (searchText.Length > 0 && searchStart >= 0)
{
if (searchEnd > searchStart || searchEnd == -1)
{
int indexToText = richTextBox1.Find(searchText, searchStart, searchEnd, RichTextBoxFinds.MatchCase);
if (indexToText >= 0)
{
returnValue = indexToText;
}
}
}
return returnValue;
}
Use a Button or TextChangeListener and Search for your word.
private void button1_Click(object sender, EventArgs e)
{
// Select the first char in your Richtextbox
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = richTextBox1.TextLength;
// Select until the end
richTextBox1.SelectionColor = Color.Black;
// Make the Text Color black
//Use an Inputfield to add the searching word
var word = txtSearch.Text;
//verify the minimum length otherwise it may freeze if you dont have text inside
if (word.Length > 3)
{
int s_start = richTextBox1.SelectionStart, startIndex = 0, index;
while ((index = FindMyText(word, startIndex, richTextBox1.TextLength)) != -1)
{
// goes through all possible found words and color them blue (starting index to end)
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionColor = Color.Blue;
startIndex = index + word.Length;
}
// Color everything between in color black to highlight only found words
richTextBox1.SelectionStart = startIndex;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = Color.Black;
}
}
I would highly recommend to set a minimum word length to avoid freezing and high memory allocation.

Categories