UndoRedo.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace CommonFroms
  6. {
  7. public class UndoRedoManager
  8. {
  9. private Stack<Command> cmd_undo_list = new Stack<Command>();
  10. private Stack<Command> cmd_redo_list = new Stack<Command>();
  11. public bool CanUndo { get { return cmd_undo_list.Count > 0; } }
  12. public bool CanRedo { get { return cmd_redo_list.Count > 0; } }
  13. public int UndoCount { get { return cmd_undo_list.Count; } }
  14. public int RedoCount { get { return cmd_redo_list.Count; } }
  15. public Command Execute(Action<object> redo, Action<object> undo, object state = null, string text = null)
  16. {
  17. var cmd = new Command(redo, undo, state);
  18. cmd.Text = text;
  19. cmd.Execute();
  20. cmd_undo_list.Push(cmd);
  21. return cmd;
  22. }
  23. public void Undo()
  24. {
  25. if (cmd_undo_list.Count > 0)
  26. {
  27. var cmd = cmd_undo_list.Pop();
  28. cmd.UnExecute();
  29. cmd_redo_list.Push(cmd);
  30. }
  31. }
  32. public void Redo()
  33. {
  34. if (cmd_redo_list.Count > 0)
  35. {
  36. var cmd = cmd_redo_list.Pop();
  37. cmd.Execute();
  38. cmd_undo_list.Push(cmd);
  39. }
  40. }
  41. }
  42. public class Command
  43. {
  44. public readonly object state;
  45. public readonly Action<object> Redo;
  46. public readonly Action<object> Undo;
  47. public string Text;
  48. internal Command(Action<object> redo, Action<object> undo, object st)
  49. {
  50. this.Redo = redo;
  51. this.Undo = undo;
  52. this.state = st;
  53. }
  54. internal void Execute()
  55. {
  56. this.Redo(this.state);
  57. }
  58. internal void UnExecute()
  59. {
  60. this.Undo(state);
  61. }
  62. }
  63. }