自己尝试一下:
打开编辑器,输入一些文本,标记其中的一些文本,然后按N
。怎么了?标记的文本被替换为n
。
同样的事情发生在你的RichTextBox
. 这里要理解的重要一点是,通过您设置的事件,您只需添加一些功能并保持默认事件处理(由操作系统处理)不变。
因此,使用您的代码,只需按一下键即可
richTextBox1.Select(1, 3);
它选择一些字符,然后默认事件处理开始。因此有一些标记的文本被替换为N
.
因此,您只需将事件标记为由您自己处理。不使用Handled
-property,而是使用SuppressKeyPress
-property。
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
e.SuppressKeyPress = true;
}
}
文件Handled
明确指出:
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.
这里是官方文档SuppressKeyPress
。