2009-09-15 40 views

回答

10

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

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

标准的方式是,你在文本框中的土地,那么当用户键入它会自动替换现有文本

1

选择现有的文本如果你不希望使用屏蔽文本框你可以在处理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 
     } 
    } 
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 
-2

不知道是否使用KeyPress事件打乱了正常的改写过程中,也可能被特定检查按键响应之内的东西,但这不是相当于一个正常的Windows文本框应该如何表现,因为当你开始用突出显示的文本输入一个控件时,应该删除该选择,以便输入该空的空格。有一次,我看到了如果声明,我意识到我一直在寻找在完成这样的行为:

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

不知道你为什么会想保留的选择,但前面的代码是理想的,如果这就是你需要

Sal

+0

这显然不是什么OP是要求,且已存在,证明它有效,接受和高度上投票的答案。 – 2014-05-04 15:01:24

+0

,但并没有给我我正在寻找的东西 - 但这是Google给我的最好回应....意思是如果别人来找我想找的东西,并发现这篇文章他们的问题是解决 – halfacreSal 2014-05-04 16:13:04

+0

我明白了,在你的回应后我几乎感觉不好。但在这种情况下,我会建议发布问答风格问题。发布一个新问题,并在同一时间用这个答案回答。使标题完全符合你在google搜索的内容,然后你就可以开始了。您可能会发现其他人已经找到了替代方法,并且人们非常感谢您的信息并据此投票。 – 2014-05-04 23:49:39