如何将WinForms Textbox设置为覆盖模式

时间:2009-09-15 15:52:49

标签: c# winforms textbox

是否可以强制Windows窗体应用程序中的文本框以“覆盖模式”工作,即在用户键入而不是添加时更换字符?
否则,有没有一种标准的方法来获得这种行为?

6 个答案:

答案 0 :(得分:11)

尝试使用MaskedTextBox并将InsertKeyMode设置为InsertKeyMode.Overwrite。

MaskedTextBox box = ...;
box.InsertKeyMode = InsertKeyMode.Overwrite;

答案 1 :(得分:2)

标准方式是在文本框中选择现有文本,然后在用户输入时自动替换现有文本

答案 2 :(得分:2)

如果您不想使用蒙面文本框,则可以在处理KeyPress事件时执行此操作。

    private void Box_KeyPress(object sender, KeyPressEventArgs e)
    {
        TextBox Box = (sender as TextBox);
        if (Box.SelectionStart < Box.TextLength && !Char.IsControl(e.KeyChar))
        {
            int CacheSelectionStart = Box.SelectionStart; //Cache SelectionStart as its reset when the Text property of the TextBox is set.
            StringBuilder sb = new StringBuilder(Box.Text); //Create a StringBuilder as Strings are immutable
            sb[Box.SelectionStart] = e.KeyChar; //Add the pressed key at the right position
            Box.Text = sb.ToString(); //SelectionStart is reset after setting the text, so restore it
            Box.SelectionStart = CacheSelectionStart + 1; //Advance to the next char
        }
    }

答案 3 :(得分:0)

此代码似乎有错误。我发现你需要在Keypress事件中设置e.Handled,否则将插入两次字符。这是我的代码(在VB中)基于以上内容: -

Private Sub txtScreen_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtScreen.KeyPress
    If txtScreen.SelectionStart < txtScreen.TextLength AndAlso Not [Char].IsControl(e.KeyChar) Then
        Dim SaveSelectionStart As Integer = txtScreen.SelectionStart
        Dim sb As New StringBuilder(txtScreen.Text)
        sb(txtScreen.SelectionStart) = e.KeyChar
        'Add the pressed key at the right position
        txtScreen.Text = sb.ToString()
        'SelectionStart is reset after setting the text, so restore it
        'Advance to the next char
        txtScreen.SelectionStart = SaveSelectionStart + 1
        e.Handled = True
    End If
End Sub

答案 4 :(得分:0)

答案 5 :(得分:-2)

不确定使用KeyPress事件是否会影响正常的改写过程,或者可能是在KeyPress中检查的特定内容,但这并不是普通的Windows文本框应该如何表现,因为当你开始键入时使用突出显示的文本控制,应删除选择,允许您键入该空白空间。一旦我看到If语句,我意识到我正在寻找的行为是完成的:

    If tb.SelectionStart < tb.TextLength AndAlso Not [Char].IsControl(e.KeyChar) Then
        tb.SelectedText = ""
    End If

不确定为什么要保留选择,但如果您需要的话,之前的代码是理想的

萨尔