代码之家  ›  专栏  ›  技术社区  ›  Peter Lee

以编程方式模拟C#2010中RichTextBox的KeyDown事件

  •  1
  • Peter Lee  · 技术社区  · 15 年前

    如果用户使用快捷键(Ctrl+Z),这是完美的。但是如果用户单击ToolStripButton呢?

    如何在C#2010中以编程方式模拟RichTextBox的KeyDown事件。

    private void tsbUndo_Click(object sender, EventArgs e)
    {
        rtbxContent_KeyDown(rtbxContent, new KeyEventArgs(Keys.Control | Keys.Z));
    }
    
    private void tsbPaste_Click(object sender, EventArgs e)
    {
        DoPaste();
    }
    
    private void DoPaste()
    {
        rtbxContent.Paste(DataFormats.GetFormat(DataFormats.UnicodeText));
    }
    
    private void rtbxContent_KeyDown(object sender, KeyEventArgs e)
    {
        //if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
        if (e.Control)
        {
            switch (e.KeyCode)
            {
                // I want my application use my user-defined behavior as DoPaste() does
                case Keys.V:
                    DoPaste();
                    e.SuppressKeyPress = true;
                    break;
    
                // I want my application use the default behavior as the RichTextBox control does
                case Keys.A:
                case Keys.X:
                case Keys.C:
                case Keys.Z:
                case Keys.Y:
                    e.SuppressKeyPress = false;
                    break;
    
                default:
                    e.SuppressKeyPress = true;
                    break;
            }
        }
    }
    

    谢谢。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Fredrik Mörk    15 年前

    这个 RichTextBox 有一个 Undo CTRL键 + . 单击 ToolStribButton . 还有 Copy Paste CanPaste 可用于启用/禁用 ToolStripButton 对应于粘贴命令。

        2
  •  0
  •   David Anderson    15 年前

    是的,这实际上不需要写一个自定义的RichTextBox就可以完成。您可以使用 SendKeys 类,它将触发控件的关键事件

    private void DoPaste()
    {
        rtbxContent.Focus(); // You should check to make sure the Caret is in the right place
        SendKeys.Send("^V"); // ^ represents CTRL, V represents the 'V' key
    }
    

    当然,这假设您的数据存储在剪贴板中。

    推荐文章