0

我有以下代码:

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

当我按 N 键时,所选文本将替换为“n”。我在 C# 中阅读了在 RichTexbox 中选择文本会删除文本,但它没有任何效果。

我正在使用 Windows 窗体。

4

2 回答 2

1

您可能需要 e.Handled = true; 在此停止事件。

http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.handled.aspx

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
        if (e.KeyCode == Keys.N)
        {
            richTextBox1.Select(1, 3);
            e.Handled = true;
        }
}
于 2012-11-23T19:09:32.080 回答
0

自己尝试一下:
打开编辑器,输入一些文本,标记其中的一些文本,然后按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

于 2012-11-23T19:14:35.700 回答