简体   繁体   English

Richtextbox删除选定的文本

[英]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". 当我按N键时,选定的文本将替换为“ n”。 I read this Selecting text in RichTexbox in C# deletes the text ,but it had no effects. 我读到此内容在C#中的RichTexbox中选择文本会删除该文本 ,但没有任何效果。

I am using Windows Forms. 我正在使用Windows窗体。

Likely, you will need e.Handled = true; 可能需要e.Handled = true; in this to stop the event. 在此停止事件。

http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.handled.aspx http://msdn.microsoft.com/zh-CN/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;
        }
}

Try it yourself: 自己尝试:
Open up the editor, type some text, mark some of this text and press N . 打开编辑器,输入一些文本,标记一些文本,然后按N What happens? 怎么了? The marked text is replaced with n . 标记的文本替换为n
The same thing happens in your RichTextBox . 同样的事情发生在您的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. 这里要了解的重要一点是,设置事件后,您只需添加一些功能,并保留默认事件处理(由OS处理)即可。

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 . 它选择一些字符,然后启动默认事件处理。因此,有些标记的文本被N替换。
So, you simply have to mark the event as handled by yourself. 因此,您只需要将事件标记为由您自己处理即可。 Not using the Handled -property, but with the SuppressKeyPress -property. 不使用Handled -property,而是使用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: 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.

Here is the official documentation of SuppressKeyPress . 这是SuppressKeyPress官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM