Highlight all searched words - c#

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.

Related

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 can i use a numericUpDown to move to specific location text in richTextBox?

In the listView selected index i select item and display the file content in richTextBox:
void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
{
richTextBox1.Text = File.ReadAllText(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
int resultsnumber = 0;
int start = richTextBox1.SelectionStart;
int startIndex = 0;
int index = 0;
string word = textBox1.Text;
Color selectionColor = richTextBox1.SelectionColor;
word = textBox1.Text.Replace("\r\n", "\n");
while ((index = richTextBox1.Text.IndexOf(word, startIndex)) != -1)
{
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionColor = Color.Yellow;
startIndex = index + word.Length;
resultsnumber ++;
}
richTextBox1.SelectionStart = start;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = selectionColor;
label16.Text = resultsnumber.ToString();
label16.Visible = true;
numericUpDown1.Maximum = resultsnumber;
numericUpDown1.Enabled = true;
}
}
And i have the numericUpDown changedvalue event
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
}
for example if i have in the numericUpDown the maximum value of 4 that's 4 results in the richTextBox text.
Each result is in another place in the text.
What i want to do is when i move up down with the numericUpDown it will jump in the richTextBox to the result location in the text.
I think it should be that if the first result started in index 0 and ended in index 20 then jump to this result show this result.
If the third result is started in index 76 and ended in index 83 so if i selected in the numericUpDown the value 3 jump to this result location.
Ok this is what i did now it was quite easy but i have a problem reseting the variable:
It was easy to do it but i have a problem reseting the variables when selecting another item each time in the listView. I want to reset the List and also to set the numericUpDown1 to value 0 when selecting other item. But then it's going to the numericUpDown1_ValueChanged item before it's adding items to the List and throw exception since the List Count and the numericUpDown1 value are 0.
In top of form1 created a new List
private List<int> results = new List<int>();
In the listView selectedindex event:
void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
{
richTextBox1.Text = File.ReadAllText(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
results = new List<int>();
numericUpDown1.Value = 0;
int resultsnumber = 0;
int start = richTextBox1.SelectionStart;
int startIndex = 0;
int index = 0;
string word = textBox1.Text;
Color selectionColor = richTextBox1.SelectionColor;
word = textBox1.Text.Replace("\r\n", "\n");
while ((index = richTextBox1.Text.IndexOf(word, startIndex)) != -1)
{
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionColor = Color.Yellow;
startIndex = index + word.Length;
resultsnumber ++;
results.Add(startIndex);
}
richTextBox1.SelectionStart = start;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = selectionColor;
label16.Text = resultsnumber.ToString();
label16.Visible = true;
numericUpDown1.Maximum = results.Count -1;
numericUpDown1.Enabled = true;
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value];
richTextBox1.ScrollToCaret();
}
}
In the numericupdown1 valuechanged event
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (results.Count == 0)
{
MessageBox.Show("Results Count Value is 0 Check It !!!!!");
}
else
{
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value];
richTextBox1.ScrollToCaret();
}
}
When selecting first item in the listView it's fine.
But then when selecting any other item i want that the results List and the numericUpDown will be reset to empty and 0.
The problem is when i set the numericUpDown1 Value to 0 it's jumping to the valuechanged event before it's adding the results to the List so it's giving the exception.

Select next highlighted row in a gridview

Here is my current code:
private void searchBtn_Click(object sender, EventArgs e)
{
//get the search term from the textbox
String searchTerm = textBox.Text;
//if the column index is 1 the we search by code and 2 if we search by name
int columnIndex = 0;
if (codeRadioBtn.Checked)
columnIndex = 1;
else
columnIndex = 2;
gridView.ClearSelection();
int firstIndex = 0;
bool found = false;
for (int i = 0; i < gridView.Rows.Count; i++)
{
//change background color to DarkOrange for the rows that contain the searched value
if (gridView.Rows[i].Cells[columnIndex].Value.ToString().Contains(searchTerm, StringComparison.OrdinalIgnoreCase))
{
//gridView.Rows[i].Selected = true;
gridView.Rows[i].DefaultCellStyle.BackColor = Color.DarkOrange;
found = true;
if (firstIndex < 1)
{
firstIndex = i;
}
}
}
//display message if no item was found
if (!found)
MessageBox.Show("The search term was not found", "Warning");
else
// scroll grid to first highlighted row
this.gridView.Rows[firstIndex].Cells[0].Selected = true;
this.gridView.CurrentCell = this.gridView.Rows[firstIndex].Cells[0];
this.gridView.FirstDisplayedCell = this.gridView.CurrentCell;
}
I am trying to make it, onClick of the search button a second time it will set the current selected to the next highlighted row.
I have been trying for a while and can't figure it out. Any help would be greatly appreciated.
Use a List or Array to store all matches.
List<int> matchList = new List<int>();
e.g.
Whilst you are highlighting the rows, why not also add that row into a list.
gridView.Rows[i].DefaultCellStyle.BackColor = Color.DarkOrange;
matchList.add(i);
To work out whether it is the first click i.e. to load and highlight matches set a int outside of the button click to keep track of how many times you clicked the button.
int clickcount= 0;
Then after you have found and highlighted set clickcount to 1 and make sure you don't highlight again using an if statement, but instead run the below loop.
if (clickcount != 0 && clickcount !=matchList.Count-1)
{
this.gridView.CurrentCell = this.gridView.Rows[clickcount].Cells[0];
clickcount++;
}
else
{
clickcount = 0;
}
Full Example
int clickcount = 0;
List<int> matchList = new List<int>();
protected void searchBtn_Click(object sender, EventArgs e)
{
if (clickcount == 0)
{
//get the search term from the textbox
String searchTerm = textBox.Text;
//if the column index is 1 the we search by code and 2 if we search by name
int columnIndex = 0;
if (codeRadioBtn.Checked)
columnIndex = 1;
else
columnIndex = 2;
gridView.ClearSelection();
int firstIndex = 0;
bool found = false;
for (int i = 0; i < gridView.Rows.Count; i++)
{
//change background color to DarkOrange for the rows that contain the searched value
if (gridView.Rows[i].Cells[columnIndex].Value.ToString().Contains(searchTerm, StringComparison.OrdinalIgnoreCase))
{
//gridView.Rows[i].Selected = true;
this.gridView.CurrentCell = gridView.Rows[0].Cells[0];
gridView.Rows[i].DefaultCellStyle.BackColor = Color.DarkOrange;
matchList.Add(i);
found = true;
if (firstIndex < 1)
{
firstIndex = i;
}
}
}
//display message if no item was found
if (!found)
{
MessageBox.Show("The search term was not found", "Warning");
}
//add one to the count to stop the search happing again.
clickcount = 1;
}
else
{
//if clickcount = 1+ or your've reached the end of your match list count
if (clickcount != 0 && clickcount != matchList.Count - 1)
{
//gridView.Rows[clickcount].DefaultCellStyle.BackColor = Color.Red;
this.gridView.CurrentCell = gridView.Rows[matchList[clickcount]].Cells[0];
clickcount++;
}
else
{
MessageBox.Show("No More Found");
clickcount = 0;
matchList.Clear();
}
}
}

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

c# wpf richtextbox selection

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

Categories