Progress.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System.ComponentModel;
  2. using System.Windows.Media.Imaging;
  3. namespace InABox.WPF
  4. {
  5. public class ProgressSection
  6. {
  7. public ProgressSection(string message, Action action)
  8. {
  9. Message = message;
  10. Action = action;
  11. }
  12. public string Message { get; set; }
  13. public Action Action { get; set; }
  14. }
  15. public static class Progress
  16. {
  17. private static ProgressForm form;
  18. public static BitmapImage DisplayImage { get; set; }
  19. public static bool IsVisible => form != null;
  20. public static string Message => form?.GetMessage();
  21. public static void ShowModal(params ProgressSection[] sections)
  22. {
  23. if (!sections.Any())
  24. return;
  25. var progress = new ProgressForm();
  26. progress.DisplayImage = DisplayImage;
  27. progress.Activated += (_, args) =>
  28. {
  29. progress.Dispatcher.Invoke(() =>
  30. {
  31. foreach (var section in sections)
  32. {
  33. progress.Progress.Content = section.Message;
  34. section.Action();
  35. }
  36. progress.Close();
  37. });
  38. };
  39. progress.ShowActivated = true;
  40. progress.ShowDialog();
  41. }
  42. public static void ShowModal(string message, Action<IProgress<string>> work)
  43. {
  44. var progress = new ProgressForm();
  45. progress.DisplayImage = DisplayImage;
  46. progress.Progress.Content = message;
  47. progress.Loaded += (_, args) =>
  48. {
  49. var worker = new BackgroundWorker();
  50. var update = new Progress<string>(data => progress.Progress.Content = data);
  51. worker.DoWork += (o, e) => work(update);
  52. worker.RunWorkerCompleted +=
  53. (o, e) => progress.Close();
  54. worker.RunWorkerAsync();
  55. };
  56. progress.ShowDialog();
  57. }
  58. public static void Show(string message)
  59. {
  60. if (form == null)
  61. {
  62. form = new ProgressForm();
  63. form.DisplayImage = DisplayImage;
  64. form.Show();
  65. }
  66. form.UpdateWindow(message);
  67. }
  68. public static void SetMessage(string message)
  69. {
  70. form.UpdateWindow(message);
  71. }
  72. public static void Close()
  73. {
  74. form?.CloseWindow();
  75. form = null;
  76. }
  77. }
  78. }