Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

winforms

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.

like image 439
broke Avatar asked Jun 13 '14 18:06

broke


1 Answers

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

maskedTextBox1.SelectionStart
    = maskedTextBox1.MaskedTextProvider.LastAssignedPosition + 1;
maskedTextBox1.SelectionLength = 0;
like image 99
BartoszKP Avatar answered Oct 15 '22 09:10

BartoszKP