c# wpf richtextbox selection
I have a RichTextBox with for example this piece o开发者_如何学编程f 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));
}
}
}
精彩评论