我希望能够覆盖在插入的文本框中定位插入符的默认行为。

默认情况下,将插入符号放在单击鼠标的位置,屏蔽文本框已包含由于掩码而产生的字符。

我知道你可以隐藏这个 post ,当控件获得焦点时,是否有类似于在文本框开头放置插入符号的东西。

有帮助吗?

解决方案

这应该可以解决问题:

    private void maskedTextBox1_Enter(object sender, EventArgs e)
    {
        this.BeginInvoke((MethodInvoker)delegate()
        {
            maskedTextBox1.Select(0, 0);
        });         
    }

其他提示

要改进Abbas的工作解决方案,请尝试以下方法:

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

此事件处理程序可以重复使用多个框,并且它不会消除用户将光标定位在输入数据中间的能力(即,当框不是时,不会强制光标移动到零位置空)。

我发现这更接近于模仿标准文本框。只剩下毛刺(我可以看到)是在'Enter'事件之后,如果xe按住鼠标并拖动到最后,用户仍然可以选择其余的(空)掩码提示。

这是对MaskedTextBoxes默认行为的重大改进。谢谢!

我对Ishmaeel的优秀解决方案做了一些改动。我更喜欢只在需要移动光标时才调用BeginInvoke。我还从各种事件处理程序调用该方法,因此输入参数是活动的MaskedTextBox。

private void    maskedTextBoxGPS_Click( object sender, EventArgs e )
{
    PositionCursorInMaskedTextBox( maskedTextBoxGPS );
}


private void    PositionCursorInMaskedTextBox( MaskedTextBox mtb )
{
  if (mtb == null)    return;

  int pos = mtb.SelectionStart;

  if (pos > mtb.Text.Length)
    this.BeginInvoke( (MethodInvoker)delegate()  { mtb.Select( mtb.Text.Length, 0 ); });
}

部分答案:您可以通过在MouseClick事件中为控件分配0长度选项来定位插入符,例如:

MaskedTextBox1.Select(5, 0)

...会将插入符号设置在文本框的第5个字符位置。

这个答案只是部分的原因是因为我无法想出一种通常可靠的方法来确定插入符号应该位于点击上的位置。对于某些面具来说这可能是可能的,但在一些常见的情况下(例如美国电话号码掩码),我真的不能想到一种简单的方法来分离掩码并提示字符与实际用户输入......

//not the prettiest, but it gets to the first non-masked area when a user mounse-clicks into the control
private void txtAccount_MouseUp(object sender, MouseEventArgs e)
{
  if (txtAccount.SelectionStart > txtAccount.Text.Length)
    txtAccount.Select(txtAccount.Text.Length, 0);
}

此解决方案适合我。请试一试。

private void maskedTextBox1_Click(object sender, EventArgs e)
{

 maskedTextBox1.Select(maskedTextBox1.Text.Length, 0);
}

我使用Click事件让我工作....不需要调用。

 private void maskedTextBox1_Click(object sender, EventArgs e)
{
     maskedTextBox1.Select(0, 0);              
}

此解决方案使用了像Gman Cornflake一样的MaskedTextBox的Click方法;但是,我发现有必要允许用户在MaskedTextBox包含数据并且光标停留在原处后单击其内部。

以下示例关闭提示和文字并评估MaskedTextBox中数据的长度,如果等于0,则将光标置于起始位置;否则它只是绕过将光标放在起始位置的代码。

代码是用VB.NET 2017编写的。希望这会有所帮助!

Private Sub MaskedTextBox1_Click(sender As Object, e As EventArgs) Handles MaskedTextBox1.Click
    Me.MaskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals
    If Me.MaskedTextBox1.Text.Length = 0 Then
        MaskedTextBox1.Select(0, 0)
    End If
    Me.MaskedTextBox1.TextMaskFormat = MaskFormat.IncludePromptAndLiterals
End Sub
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top