How to capture the cursor position in a textbox?

Question

I have a TextChanged event on my Masked TextBox and I want that its method be called just when the cursor stay at the end.

For example:

222.222.2/21

The event shall be called as soon as the user types "1".

XAML

<TextBox
                Name="myTextBox"
                ToolTip="type here"
                Height="30"
                Width="100"
                FontSize="14"
                MaxLength="12"
                HorizontalContentAlignment="Right"
                TextChanged="MyMethod"/>

C#

 private void MyMethod(object sender, EventArgs e){
     if (myTextBox.Text.Length == myTextBox.MaxLength)
        {
            //how do I know if the cursor is at the end?
        }
    }

SOLUTION

private void MyMethod(object sender, EventArgs e){
     if (myTextBox.Text.Length == myTextBox.MaxLength)
        {
            if(processo.CaretIndex == 12)
            {
               //do something
            }
        }
    }

Show source
| c#   | wpf   | xaml   | events   | textbox   2017-09-05 22:09 1 Answers

Answers to How to capture the cursor position in a textbox? ( 1 )

  1. 2017-09-05 22:09

    You can use myTextBox.CaretIndex.

    private void MyMethod(object sender, EventArgs e)
    {
        if (myTextBox.Text.Length == myTextBox.MaxLength)
        {
            System.Diagnostics.Debug.WriteLine($"caret is at {myTextBox.CaretIndex}");
        }
    }
    

Leave a reply to - How to capture the cursor position in a textbox?

◀ Go back