2

I want to have the x, y position of the last character in a TextBox. I found GetCharacterIndexFromPoint method which exactly is a reverse approach. => here

However, I couldn't find the appropriate approach for getting actual position of last character within a TextBox.

Does anyone know how I can get such information?

Community
  • 1
  • 1
Sehi
  • 21
  • 2
  • Please explain what are you trying to do – Gilad Aug 03 '15 at 09:32
  • Have you tried to look at the GetCharacterIndexFromPoint sources? – Liero Aug 03 '15 at 12:20
  • @Gliad I'm trying to implement a blinking caret without focusing on the TextBox. Since I couldn't find a method for showing caret without focusing, I'm now trying to simulate caret after the last character using animation. – Sehi Aug 04 '15 at 02:31

1 Answers1

0

This question is pretty old now, but I want to give it a try.

My solution for getting the actual position of last character within a TextBox:

MainWindow.xaml:

<StackPanel>
    <Label Margin="10" HorizontalAlignment="Center" Content="Enter First Text: " FontSize="20"/>
    <TextBox Name="TextBox" Margin="10" Width="200" LostFocus="TextBox_OnLostFocus"/>
    <Button Content="GetPositionFromLastCharacter" Width="200" Click="GetLastCharacterFromTextBox"/>
    <Label Margin="10" HorizontalAlignment="Center" Content="Enter second Text: " FontSize="20"/>
    <TextBox Margin="10" Width="200"/>
</StackPanel>

Method "GetLastCharacterFromTextBox" in MainWindow.xaml.cs

private void GetLastCharacterFromTextBox(object sender, RoutedEventArgs e)
{
    int lastCharacterPosition = TextBox.Text.LastIndexOf(TextBox.SelectedText, StringComparison.CurrentCulture);
    MessageBox.Show($"Last character from the Text is at position: {lastCharacterPosition}");
}

Output: WPF Application running

As you can see, I used the "LastIndexOf" Method with the selected text in the TextBox.

Suggestion for showing caret without focusing:

Use the "LostFocus" property on a TextBox and implement the following code:

private void TextBox_OnLostFocus(object sender, RoutedEventArgs e)
{
    e.Handled = true;
}

The result is the following: Showing caret without focus

Even though I have no focus on the first TextBox anymore, the caret is still visible.

Stan1k
  • 338
  • 2
  • 17