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.
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 withn.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
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 theSuppressKeyPress-property.The documentation of
Handledclearly states:Here is the official documentation of
SuppressKeyPress.