ProgressHelperOld.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace PTMedicalInsurance.Common
  9. {
  10. public class ProgressHelper
  11. {
  12. private readonly BackgroundWorker _backgroundWorker;
  13. private readonly System.Windows.Forms.ProgressBar _progressBar;
  14. private Action<int> _updateProgressAction;
  15. public ProgressHelper(System.Windows.Forms.ProgressBar progressBar)
  16. {
  17. _progressBar = progressBar;
  18. _backgroundWorker = new BackgroundWorker
  19. {
  20. WorkerReportsProgress = true,
  21. WorkerSupportsCancellation = true
  22. };
  23. _backgroundWorker.DoWork += BackgroundWorker_DoWork;
  24. _backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
  25. _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
  26. }
  27. // 启动进度条,传入要执行的工作方法和是否需要显示具体进度
  28. public void Start(Action workMethod, bool showSpecificProgress = false)
  29. {
  30. if (_backgroundWorker.IsBusy) return;
  31. _progressBar.Style = showSpecificProgress ? ProgressBarStyle.Continuous : ProgressBarStyle.Marquee;
  32. _progressBar.Value = 0;
  33. _backgroundWorker.RunWorkerAsync(new { WorkMethod = workMethod, ShowSpecificProgress = showSpecificProgress });
  34. }
  35. // 更新进度条(仅当显示具体进度时)
  36. public void UpdateProgress(int percentage)
  37. {
  38. if (_backgroundWorker.CancellationPending) return;
  39. if (_updateProgressAction != null)
  40. {
  41. _updateProgressAction(percentage);
  42. }
  43. }
  44. // 取消正在进行的操作
  45. public void Cancel()
  46. {
  47. if (!_backgroundWorker.CancellationPending)
  48. {
  49. _backgroundWorker.CancelAsync();
  50. }
  51. }
  52. private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  53. {
  54. var parameters = (dynamic)e.Argument;
  55. var workMethod = parameters.WorkMethod;
  56. var showSpecificProgress = parameters.ShowSpecificProgress;
  57. try
  58. {
  59. if (showSpecificProgress)
  60. {
  61. _updateProgressAction = progress => ((BackgroundWorker)sender).ReportProgress(progress);
  62. }
  63. workMethod(); // 执行传入的工作方法
  64. }
  65. catch (Exception ex)
  66. {
  67. MessageBox.Show($"An error occurred: {ex.Message}");
  68. e.Cancel = true;
  69. }
  70. finally
  71. {
  72. _updateProgressAction = null;
  73. }
  74. }
  75. private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
  76. {
  77. _progressBar.Value = e.ProgressPercentage;
  78. }
  79. private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  80. {
  81. if (!e.Cancelled && (e.Error != null))
  82. {
  83. _progressBar.Value = 0;
  84. _progressBar.Style = ProgressBarStyle.Continuous;
  85. }
  86. }
  87. }
  88. public class OverlayProgressBarManager
  89. {
  90. private ProgressBar progressBar;
  91. private Form form;
  92. private Form frm = new Form();
  93. public OverlayProgressBarManager(Form form)
  94. {
  95. this.form = form;
  96. progressBar = new ProgressBar();
  97. progressBar.Style = ProgressBarStyle.Marquee; // Set the style to Marquee.
  98. progressBar.MarqueeAnimationSpeed = 30; // Adjust speed of animation.
  99. progressBar.Visible = false;
  100. progressBar.Anchor = AnchorStyles.None; // Do not anchor to any edge.
  101. //form.Controls.Add(progressBar);
  102. //form.Resize += OnFormResize; // Handle form resize event.
  103. frm.Width = 2000;
  104. frm.Left = 20;
  105. frm.Height = 200;
  106. frm.Controls.Add(progressBar);
  107. frm.Resize += OnFormResize; // Handle form resize event.
  108. CenterProgressBar(); // Initially center the progress bar.
  109. }
  110. private void OnFormResize(object sender, EventArgs e)
  111. {
  112. CenterProgressBar();
  113. }
  114. private void CenterProgressBar()
  115. {
  116. if (progressBar.Parent != null && !progressBar.Parent.IsDisposed)
  117. {
  118. progressBar.Left = (progressBar.Parent.ClientSize.Width - progressBar.Width) / 2;
  119. progressBar.Top = (progressBar.Parent.ClientSize.Height - progressBar.Height) / 2;
  120. }
  121. }
  122. public void Start()
  123. {
  124. progressBar.Visible = true;
  125. progressBar.MarqueeAnimationSpeed = 30; // Restart the animation.
  126. CenterProgressBar(); // Ensure it's centered when started.
  127. frm.ShowDialog();
  128. }
  129. public void Stop()
  130. {
  131. //progressBar.MarqueeAnimationSpeed = 0; // Stop the animation.
  132. //progressBar.Visible = false;
  133. frm.Close();
  134. }
  135. }
  136. public class ProgressDialog : Form
  137. {
  138. private ProgressBar progressBar1;
  139. private Label labelStatus;
  140. public ProgressDialog()
  141. {
  142. Application.EnableVisualStyles();
  143. this.Text = "正在查询...";
  144. this.StartPosition = FormStartPosition.CenterParent;
  145. this.FormBorderStyle = FormBorderStyle.FixedDialog;
  146. this.MaximizeBox = false;
  147. this.MinimizeBox = false;
  148. this.ShowInTaskbar = false;
  149. this.TopMost = true; // 确保进度条始终在最前面
  150. this.CenterToScreen();
  151. progressBar1 = new ProgressBar
  152. {
  153. Location = new System.Drawing.Point(12, 12),
  154. Size = new System.Drawing.Size(260, 23)
  155. };
  156. progressBar1.Style = ProgressBarStyle.Marquee;
  157. progressBar1.MarqueeAnimationSpeed = 50;
  158. Controls.Add(progressBar1);
  159. labelStatus = new Label
  160. {
  161. Location = new System.Drawing.Point(12, 41),
  162. Size = new System.Drawing.Size(260, 23)
  163. };
  164. Controls.Add(labelStatus);
  165. // 设置默认样式
  166. SetStyle(ControlStyles.ResizeRedraw, true);
  167. ClientSize = new System.Drawing.Size(284, 75);
  168. }
  169. // 允许外部设置进度条的值
  170. public int ProgressValue
  171. {
  172. set { if (InvokeRequired) Invoke(new Action(() => progressBar1.Value = value)); else progressBar1.Value = value; }
  173. }
  174. // 允许外部设置状态文本
  175. public string StatusText
  176. {
  177. set { if (InvokeRequired) Invoke(new Action(() => labelStatus.Text = value)); else labelStatus.Text = value; }
  178. }
  179. //异步展示
  180. public async void ShowAsync()
  181. {
  182. await Task.Run(() => progressBar1.Show());
  183. }
  184. }
  185. //public class DataLoader
  186. //{
  187. // private ProgressDialog progressDialog;
  188. // public DataLoader(Func<Task> loadDataAsync)
  189. // {
  190. // this.loadDataAsync = loadDataAsync ?? throw new ArgumentNullException(nameof(loadDataAsync));
  191. // }
  192. // private readonly Func<Task> loadDataAsync;
  193. // // 执行数据加载操作
  194. // public async Task ExecuteLoadOperation()
  195. // {
  196. // progressDialog = new ProgressDialog();
  197. // // 使用 BeginInvoke 确保 Show 在正确的线程上调用
  198. // if (progressDialog.InvokeRequired)
  199. // {
  200. // progressDialog.BeginInvoke(new Action(() => progressDialog.ShowDialog()));
  201. // }
  202. // else
  203. // {
  204. // progressDialog.Show();
  205. // }
  206. // try
  207. // {
  208. // // 执行传入的数据加载操作
  209. // await loadDataAsync();
  210. // progressDialog.DialogResult = DialogResult.OK;
  211. // }
  212. // finally
  213. // {
  214. // // 确保即使发生异常也会关闭进度框
  215. // CloseProgressDialog();
  216. // }
  217. // }
  218. // private void CloseProgressDialog()
  219. // {
  220. // if (progressDialog != null && !progressDialog.IsDisposed)
  221. // {
  222. // // 使用 BeginInvoke 确保 Close 在正确的线程上调用
  223. // if (progressDialog.InvokeRequired)
  224. // {
  225. // progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
  226. // }
  227. // else
  228. // {
  229. // progressDialog.Close();
  230. // }
  231. // }
  232. // }
  233. ////}
  234. public class DataLoader : IDisposable
  235. {
  236. private readonly BackgroundWorker _backgroundWorker = new BackgroundWorker();
  237. public delegate int MyFunc<T1>(out T1 err);
  238. private MyFunc<string> _queryExportDataAction;
  239. private ProgressDialog progressDialog = new ProgressDialog();
  240. private Form mainForm;
  241. public DataLoader(MyFunc<string> queryExportDataAction,Form frm)
  242. {
  243. mainForm = frm;
  244. _queryExportDataAction = queryExportDataAction ?? throw new ArgumentNullException(nameof(queryExportDataAction));
  245. // 配置 BackgroundWorker
  246. _backgroundWorker.WorkerReportsProgress = true;
  247. _backgroundWorker.WorkerSupportsCancellation = true;
  248. _backgroundWorker.DoWork += BackgroundWorker_DoWork;
  249. _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
  250. }
  251. public void StartQueryExportData(Action<int, string> onCompleted)
  252. {
  253. if (mainForm == null)
  254. {
  255. progressDialog.Show();
  256. }
  257. else
  258. {
  259. progressDialog.Show(mainForm);
  260. }
  261. if (_backgroundWorker.IsBusy) return;
  262. this._onCompleted = onCompleted;
  263. _backgroundWorker.RunWorkerAsync();
  264. }
  265. private Action<int, string> _onCompleted;
  266. private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  267. {
  268. // 调用传入的方法
  269. string errMsg = "";
  270. int result = _queryExportDataAction(out errMsg);
  271. e.Result = Tuple.Create(result, errMsg);
  272. }
  273. private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  274. {
  275. progressDialog.Close();
  276. if (e.Error != null)
  277. {
  278. // 处理错误
  279. MessageBox.Show($"An error occurred: {e.Error.Message}");
  280. }
  281. else if (e.Cancelled)
  282. {
  283. // 处理取消的情况
  284. MessageBox.Show("Operation was cancelled.");
  285. }
  286. else
  287. {
  288. var resultTuple = (Tuple<int, string>)e.Result;
  289. int result = resultTuple.Item1;
  290. string errMsg = resultTuple.Item2;
  291. // 调用回调函数,传递结果和错误信息
  292. _onCompleted?.Invoke(result, errMsg);
  293. }
  294. }
  295. public void Dispose()
  296. {
  297. _backgroundWorker.Dispose();
  298. }
  299. }
  300. }