Simulate a KeyPress in C# code

Jul 19 2011 9:33 AM
Hi,

I am trying to develop a text editor in C#. I want it to record and replay macros. This is how I am trying to do it:

The Bool MacroRecording keeps track of whether it is usual business.. or recording a macro. Pressing ^Q starts recording a macro.. and ^Q again stops it... the set of key press events are stored in a list MacroKeyList .. and on ^P , the recorded list of keys should be played.. 

I am able to record the MacroKeyList. On ^P, it tries to play the set of keys.. but nothing happens !! It does not reflect on the text box.

Possibly something wrong in the way I am trying to play the recorded macro. Could you please correct ?

Here is my code...

private void MyRichTextBox_KeyDown(object sender, KeyEventArgs e)
{
  if (e.Control)
  {
    if (e.KeyCode == Keys.Q)
    {
      if (MacroRecording)
        MacroRecording = false;
      else
      {
        MessageBox.Show("Start Recording");
        MacroKeyList.Clear();
        MacroRecording = true;
      }
    }
    else if (e.KeyCode == Keys.P)
    {
      if (MacroKeyList.Count > 0)
      {
         foreach (KeyPressEventArgs a in MacroKeyList)
            OnKeyPress(a);
      }
    }
  }
}

private void MyRichTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
   if (MacroRecording) MacroKeyList.Add(e);
}


Answers (4)