Undo all actions of a button VSTO

Viewed 231

I am developing a MS Word Add-In, so I added a button that fires a function :

private void button1_Click(object sender, RibbonControlEventArgs e) {
    // do some actions on a word document (text - formatting - ...) here.
}

My issue is, when the funcation performs n actions on the word document, I have to click undo n times to undo all button actions. This is a bad user experience to undo like 10 or 100 times to return to original state (text - formatting - ... etc).

Is there some way to pack all button actions as one action in the undo stack, so that I can undo button effect with a single click or Ctrl + z ?

Important note:

An alternative approach that does the job for me is to:

  • Open temp document.
  • Copy original document to temp document.
  • Do all edits on temp doc ( n actions taken on it).
  • Copy temp doc back to original doc (only one action taken which is paste, so I can undo it).

This is why I struggled in the second approach: check here

2 Answers

You could wrap everything in a custom undo-record - that way you only have to undo once to undo it all.

Visual Basic:

Application.UndoRecord.StartCustomRecord "Title of undo-record here"
Application.ScreenUpdating = False ' Optional, reduces screen flicker during operations.

'--- Your code here

Application.ScreenUpdating = True ' Optional, but required if set to false above
Application.UndoRecord.EndCustomRecord

' After this, you can undo once to undo it all.

C#:

Application.UndoRecord.StartCustomRecord "Title of undo-record here";
Application.ScreenUpdating = false; // Optional, reduces screen flicker during operations.

//--- Your code here

Application.ScreenUpdating = true; // Optional, but required if set to false above
Application.UndoRecord.EndCustomRecord;

// After this, you can undo once to undo it all.
Related