Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position the caret in a MaskedTextbox

I would like to be able to override the default behaviour for positioning the caret in a masked textbox.

The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask.

I know that you can hide the caret as mentioned in this post, is there something similar for positioning the caret at the beginning of the textbox when the control gets focus.

like image 770
benPearce Avatar asked Sep 23 '08 05:09

benPearce


2 Answers

This should do the trick:

    private void maskedTextBox1_Enter(object sender, EventArgs e)
    {
        this.BeginInvoke((MethodInvoker)delegate()
        {
            maskedTextBox1.Select(0, 0);
        });         
    }
like image 54
Abbas Avatar answered Nov 20 '22 04:11

Abbas


To improve upon Abbas's working solution, try this:

private void ueTxtAny_Enter(object sender, EventArgs e)
{
    //This method will prevent the cursor from being positioned in the middle 
    //of a textbox when the user clicks in it.
    MaskedTextBox textBox = sender as MaskedTextBox;

    if (textBox != null)
    {
        this.BeginInvoke((MethodInvoker)delegate()
        {
            int pos = textBox.SelectionStart;

            if (pos > textBox.Text.Length)
                pos = textBox.Text.Length;

            textBox.Select(pos, 0);
        });
    }
}

This event handler can be re-used with multiple boxes, and it doesn't take away the user's ability to position the cursor in the middle of entered data (i.e does not force the cursor into zeroeth position when the box is not empty).

I find this to be more closely mimicking a standard text box. Only glitch remaining (that I can see) is that after 'Enter' event, the user is still able to select the rest of the (empty) mask prompt if xe holds down the mouse and drags to the end.

like image 10
Ishmaeel Avatar answered Nov 20 '22 03:11

Ishmaeel