问题
Is it possible to force a textbox in a windows forms application to work in "overwrite mode", i.e. have characters replaced when the user types instead of added?
Otherwise, is there a standard way to get this behavior?
回答1:
Try using a MaskedTextBox and set InsertKeyMode to InsertKeyMode.Overwrite.
MaskedTextBox box = ...;
box.InsertKeyMode = InsertKeyMode.Overwrite;
回答2:
Standard way would be to select the existing text as you land in the textbox, then as the user types it will automatically replace the existing text
回答3:
If you do not wish to use a Masked textbox you can do this when handling the KeyPress event.
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
}
}
回答4:
This code seems to have an error. I found that you need to set e.Handled in the Keypress event, otherwise the character is inserted twice. Here is my code (in VB) based on the above: -
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
回答5:
You could use a RichTextBox
instead of a TextBox
.
Source: https://social.msdn.microsoft.com/Forums/en-US/966c3af9-6674-4f48-b487-7afbef05f0cb/overwrite-mode-in-a-textbox
回答6:
Not sure if using the KeyPress event messes up the normal overtype process, or maybe something specific being checked for within KeyPress, but this isn't quite how a normal windows text box should behave, in that when you start typing in a control with highlighted text, the selection should be removed, allowing you to type in that emptied space. Once I saw the If statement I realised the behaviour I was looking for was accomplished doing this:
If tb.SelectionStart < tb.TextLength AndAlso Not [Char].IsControl(e.KeyChar) Then
tb.SelectedText = ""
End If
not sure why you would want to preserve the selection, but the previous code is ideal if that's what you need
Sal
来源:https://stackoverflow.com/questions/1428047/how-to-set-winforms-textbox-to-overwrite-mode