简体   繁体   中英

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
            }
        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM