【问题标题】:Richtextbox deletes selected textRichtextbox 删除选中的文本
【发布时间】:2012-11-23 19:06:58
【问题描述】:

我有以下代码:

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

当我按 N 键时,选定的文本将替换为“n”。我读了这个Selecting text in RichTexbox in C# deletes the text,但没有任何效果。

我正在使用 Windows 窗体。

【问题讨论】:

    标签: c# winforms richtextbox keyevent


    【解决方案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;
            }
    }
    

    【讨论】:

      【解决方案2】:

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

      documentation of 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.
      

      这里是official documentation of SuppressKeyPress

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-02
        • 2013-08-12
        • 2014-03-11
        相关资源
        最近更新 更多