How to set WinForms text field to overwrite mode

Is it possible to make a text field in a Windows forms application work in "rewritable mode", i.e. replace characters when user types instead of adding?
Otherwise, is there a standard way to get this behavior?

+3
source share
6 answers

Try using MaskedTextBox and set InsertKeyMode to InsertKeyMode.Overwrite.

MaskedTextBox box = ...;
box.InsertKeyMode = InsertKeyMode.Overwrite;
+10
source

The standard way would be to select existing text when you land in a text field, and then when the user enters it, it will automatically replace the existing text

+2

Masked, 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
        }
    }
+1

. , e.Handled Keypress, . ( 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
0

, KeyPress , , - , KeyPress, , Windows, , , . If, , , , :

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

, , ,

Sal

-2

Source: https://habr.com/ru/post/1717738/


All Articles