Beetlejuice
Beetlejuice

Reputation: 4425

Overwrite characters in a TextBox

When I type in this textbox, I need that the default behavior is overwrite, instead insert. I don´t know if I made my self clear.

For example: I have a textbox with MaxLenght = 4. When it get focus, it need to overwrite chars, from the first to last.

I can do this using the "Insert" button. But I need an automatic solution.

Upvotes: 0

Views: 2779

Answers (2)

TrueEddie
TrueEddie

Reputation: 2233

You could try handling the key down event, for example:

private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
    int myCaretIndex = MyTextBox.CaretIndex;
    char[] characters = MyTextBox.Text.ToCharArray();

    if (myCaretIndex < characters.Length)
    {
        characters[myCaretIndex] = char.Parse(e.Key.ToString());

        MyTextBox.Text = string.Join("", characters);

        MyTextBox.CaretIndex = myCaretIndex + 1;

        e.Handled = true;
    }
}

Upvotes: 1

Rohit Vats
Rohit Vats

Reputation: 81313

You can do that using reflection by setting _OvertypeMode to True on TextEditor property of TextBox.

Suppose you have TextBox declaration in XAML:

<TextBox x:Name="textBox"/>

and in code behind, you can do:

PropertyInfo textEditorProperty = typeof(TextBox).GetProperty(
                  "TextEditor", BindingFlags.NonPublic | BindingFlags.Instance);

object textEditor = textEditorProperty.GetValue(textBox, null);

// set _OvertypeMode on the TextEditor
PropertyInfo overtypeModeProperty = textEditor.GetType().GetProperty(
               "_OvertypeMode", BindingFlags.NonPublic | BindingFlags.Instance);

overtypeModeProperty.SetValue(textEditor, true, null);

Source - MSDN link.

Upvotes: 1

Related Questions