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?
Try using a MaskedTextBox and set InsertKeyMode to InsertKeyMode.Overwrite.
MaskedTextBox box = ...;
box.InsertKeyMode = InsertKeyMode.Overwrite;
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
}
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With