// returns a rect for selected text
// if no text is selected, returns caret location
// textbox should not be empty
private Rect GetTextboxSelectionRect(TextBox textbox)
{
Rect rectFirst, rectLast;
if (textbox.SelectionStart == textbox.Text.Length)
{
rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart - 1, true);
}
else
{
rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart, false);
}
int lastIndex = textbox.SelectionStart + textbox.SelectionLength;
if (lastIndex == textbox.Text.Length)
{
rectLast = textbox.GetRectFromCharacterIndex(lastIndex - 1, true);
}
else
{
rectLast = textbox.GetRectFromCharacterIndex(lastIndex, false);
}
rectFirst.Union(rectLast);
GeneralTransform transform = textbox.TransformToVisual(null);
return transform.TransformBounds(rectFirst);
}