views:

167

answers:

2

Hi,

I have a RichTextBox on my form, and I want to use the default behavior as the RichTextBox does, such as, Ctrl+Z (Undo) or other actions (Ctrl+Y, Ctrl+X, Ctrl+V).

If users use the shortcut keys (Ctrl+Z), it's perfect. But what if the users click a ToolStripButton?

How can I programmatically simulate a KeyDown Event for RichTextBox in C# 2010.

Here is the code snippet that has some issues. Can you help me on how to Simulate/RaiseEvent in C#?

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;
        }
    }
}

Thanks.

A: 

Yep, this can actually be done without writing a custom RichTextBox. Instead of calling the Paste() method on the RichTextBox, you can use the SendKeys class, which WILL trigger the key events for a control

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
}

This of course assumes your data is stored in the Clipboard.

David Anderson
Hi David, your solution is also perfect for me. It's a pity that I could not mark two correct answers. SendKeys.Send("^V"); quite useful :-)
Peter Lee
A: 

The RichTextBox has an Undo method that will do the same thing as CTRL+Z. You can call that when clicking the ToolStribButton. There are also Copy and Paste methods along with a CanPaste method that can be used for enabling/disabling the ToolStripButton corresponding to the paste command.

This way you don't need to simulate anything but instead call the functionality that produces the behavior. After all, the key presses are just triggers for that behavior.

Fredrik Mörk
Hi Fredrik, you are right that there are corresponding methods doing what I need.
Peter Lee