Search code examples
c#winformsrichtextboxkeyevent

Richtextbox deletes selected text


I have the following code:

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.N)
        {
            richTextBox1.Select(1, 3);
        }
    }

When I press the N key , the selected text is replaced with "n". I read this Selecting text in RichTexbox in C# deletes the text ,but it had no effects.

I am using Windows Forms.


Solution

  • Try it yourself:
    Open up the editor, type some text, mark some of this text and press N. What happens? The marked text is replaced with n.
    The same thing happens in your RichTextBox. Important to understand here is, that with the event you set up, you only add some functionality and leave the default event handling (handled by the OS) intact.

    So with your code, on a key press you just do

    richTextBox1.Select(1, 3);
    

    which selects some characters and afterwards the default event handling kicks in. Thus there is some marked text which gets replaced with N.
    So, you simply have to mark the event as handled by yourself. Not using the Handled-property, but with the SuppressKeyPress-property.

    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.N)
        {
            richTextBox1.Select(1, 3);
            e.SuppressKeyPress = true;
        }
    }
    

    The documentation of Handled clearly states:

    If you set Handled to true on a TextBox, that control will
    not pass the key press events to the underlying Win32 text
    box control, but it will still display the characters that the user typed.
    

    Here is the official documentation of SuppressKeyPress.