Skip to content

Instantly share code, notes, and snippets.

@yamamaya
Created July 17, 2025 08:31
Show Gist options
  • Save yamamaya/1add4d18a33b5d8fc26699b4eeaf0865 to your computer and use it in GitHub Desktop.
Save yamamaya/1add4d18a33b5d8fc26699b4eeaf0865 to your computer and use it in GitHub Desktop.
Gets the rectangle of the caret in the TextBox
using Microsoft.UI.Xaml.Controls;
using Windows.Foundation;
namespace OaktreeLab.Utils.WinUI3 {
/// <summary>
/// Class that provides extension methods for TextBox.
/// </summary>
public static class TextBoxExtensions {
/// <summary>
/// Gets the rectangle of the caret in the TextBox.
/// </summary>
/// <remarks>
/// The width of the rectangle is always zero.
/// If the text is empty, the returned rectangle is at the origin (0, 0) with zero width and height.
/// </remarks>
/// <returns>The caret's Rect</returns>
public static Rect GetCaretRect( this TextBox textBox ) {
int caretIndex = textBox.SelectionStart;
string text = textBox.Text;
Rect caretRect;
if ( text.Length == 0 ) {
// If the text is empty, return a rectangle at the origin
caretRect = new Rect( 0, 0, 0, 0 );
} else if ( caretIndex == text.Length ) {
// If the caret is at the end of the text
if ( text[ text.Length - 1 ] == '\r' ) {
// If the caret is immediately after a newline character, calculate the start position of the next line based on the previous character's rectangle
caretRect = textBox.GetRectFromCharacterIndex( caretIndex - 1, true );
caretRect.X = textBox.GetRectFromCharacterIndex( 0, false ).X;
caretRect.Y += caretRect.Height;
} else {
// If the caret is at the end of the text and not after a newline character, get the rectangle of the last character
caretRect = textBox.GetRectFromCharacterIndex( caretIndex - 1, true );
}
} else {
// If the caret is in the middle of the text, get the rectangle at the caret position
caretRect = textBox.GetRectFromCharacterIndex( caretIndex, false );
}
return caretRect;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment