Search code examples
c#wpfxamleventstextbox

How to capture the cursor position in a textbox?


I have a TextChanged event on my Masked TextBox and I want its method to 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(process.CaretIndex == 12)
            {
               //do something
            }
        }
    }

Solution

  • 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}");
        }
    }