Macro Recorder in C#

Desktop applications can often benefit by having macro recording capabilities to play back commands for repetitive actions. There is a rather simple approach in .NET to doing this when your commands are invoked by a menu item or button.

Events from clicking a menu item or a button have a very simple signature and happen to be delegates. The EventHandler type specifies a delegate of the form:

void someCommand_Click(object sender, EventArgs e)

This means that creating a list objects with a member of type EventHandler provides a way to quickly repeat a series of commands by invoking that EventHandler for each object in the list. Maybe an example would better demonstrate this. First, let's set up an object that can be used to invoke a command:

public class RecordCmd
{
    private EventHandler _handler;

    public RecordCmd(EventHandler handler)
    {
        _handler = handler;
    }

    public void Fire()
    {
        _handler(null, null);
    }
}

The Fire() method is for executing the command during playback. Now to create a recording, simply add a RecordCmd object referencing the command handler every time the command is executed during record mode.

private bool _recording;
private List<RecordCmd> _recordedCommands;

private void someCommandToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (_recording)
    {
        _recordedCommands.Add(new RecordCmd(
            new EventHandler(someCommandToolStripMenuItem_Click)));
    }

    // actual code to execute is here
}

Playback is simply a matter of going through the list and firing all of the commands. Of course, additional code can be added to this simple example to allow for more complex interaction and storage of state along with the events, but this provides a general idea of how easily a macro recorder can be added to any .NET application.

private void playbackToolStripMenuItem_Click(object sender, EventArgs e)
{
    foreach (RecordCmd cmd in _recordedCommands)
        cmd.Fire();
}