简体   繁体   English

如何将光标定位在蒙版文本框的文本末尾?

[英]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. 我知道您可以设置textmaskformat属性以排除文字,但计数仍然不正确,因为文字仍然显示。

You can use LastAssignedPosition property from the MaskedTextProvider class, available as a property of MaskedTextBox : 您可以使用MaskedTextProvider类的LastAssignedPosition属性,该属性可作为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. 这是一个非常古老的问题,但是今天我试图在我的winforms应用程序中实现相同的功能时遇到了它。

The accepted answer did work, but will position the cursor at position 0 , even if there is masked text at the beginning: XYZ______ . 接受的答案确实有效,但是将光标定位在位置0 ,即使开头有掩码文字: XYZ______

I was able to resolve this issue by using the FindUnassignedEditPositionFrom() method on MaskedTextProvider : 我能够通过在MaskedTextProvider上使用FindUnassignedEditPositionFrom()方法解决此问题:

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. 这使用与接受的答案相同的LastAssignedPosition ,但另外考虑了可能出现在开头的任何不可编辑的文本 - 简而言之,这会将光标移动到可用的第一个可编辑位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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