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
}
}
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
7条答案
按热度按时间jgzswidk1#
尝试使用MaskedTextBox并将InsertKeyMode设置为InsertKeyMode.Overwrite。
cnwbcb6i2#
如果您不希望使用Masked文本框,则可以在处理KeyPress事件时执行此操作。
s6fujrry3#
标准的方法是在文本框中选择现有文本,然后当用户键入时,它将自动替换现有文本
zaqlnxep4#
此代码似乎有一个错误。我发现你需要在Keypress事件中设置e.Handled,否则字符会被插入两次。下面是我的代码(在VB中)基于上述内容:-
zaq34kh65#
您可以使用
RichTextBox
而不是TextBox
。来源:https://social.msdn.microsoft.com/Forums/en-US/966c3af9-6674-4f48-b487-7afbef05f0cb/overwrite-mode-in-a-textbox
798qvoo86#
谢谢大家!现在这是我的了参考:https://www.syncfusion.com/faq/windowsforms/textbox/how-can-i-place-a-textbox-in-overwrite-mode-instead-of-insert-mode
我的应用回购:https://github.com/oscarsun72/TextForCtext.git
WindowsFormsApp1/Form1.cs
llew8vvj7#
不确定使用KeyPress事件是否会扰乱正常的overtype过程,或者可能是KeyPress中正在检查的特定内容,但这并不是正常的Windows文本框应该如何表现,因为当您开始键入具有高亮文本的控件时,选择应该被删除,允许您键入空的空间。当我看到If语句时,我意识到我正在寻找的行为是这样完成的:
我不知道为什么要保留选择,但如果需要的话,前面的代码是理想的
萨尔