简体   繁体   中英

How to position cursor at the end of text on a masked textbox?

I'm using a masked text-box with the phone number mask, and if you click the control, the cursor position is set wherever the mouse was clicked. I would like to override the default positioning of the cursor so that:

  1. If no text is entered, the cursor is positioned at the beginning of the textbox.

  2. If text is already entered and the control is clicked, position the cursor after the last inputted number.

Is there a way to do this?

EDIT

Some people have suggested using this code:

PhoneNumber.SelectionStart = PhoneNumber.Text.Length;

But this will not work since the mask literals are included in the length count, which screws up the cursor positioning. I know that you can set the textmaskformat property to exclude literals, but the count still wont be right because the literals are still displayed.

You can use LastAssignedPosition property from the MaskedTextProvider class, available as a property of MaskedTextBox :

maskedTextBox1.SelectionStart
    = maskedTextBox1.MaskedTextProvider.LastAssignedPosition + 1;
maskedTextBox1.SelectionLength = 0;

This is a pretty old question by now, but I came across it today while trying to implement the same in my winforms app.

The accepted answer did work, but will position the cursor at position 0 , even if there is masked text at the beginning: XYZ______ .

I was able to resolve this issue by using the FindUnassignedEditPositionFrom() method on MaskedTextProvider :

private void TextBox_Click(object sender, EventArgs e)
{
    int startPos = this.textBox.MaskedTextProvider.FindUnassignedEditPositionFrom(this.textBox.MaskedTextProvider.LastAssignedPosition + 1, true);
    this.textBox.Select(startPos, 0);            
}

This uses the same LastAssignedPosition as the accepted answer, but additionally accounts for any uneditable text that may appear at the beginning - in short, this will move the cursor to the first editable position available.

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