Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set WinForms Textbox to overwrite mode

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?

like image 271
Paolo Tedesco Avatar asked Sep 15 '09 15:09

Paolo Tedesco


4 Answers

Try using a MaskedTextBox and set InsertKeyMode to InsertKeyMode.Overwrite.

MaskedTextBox box = ...;
box.InsertKeyMode = InsertKeyMode.Overwrite;
like image 103
JaredPar Avatar answered Oct 31 '22 03:10

JaredPar


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
        }
    }
like image 34
Mike de Klerk Avatar answered Oct 31 '22 03:10

Mike de Klerk


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

like image 2
PaulG Avatar answered Oct 31 '22 05:10

PaulG


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
like image 1
Robert Barnes Avatar answered Oct 31 '22 03:10

Robert Barnes