ProgressHelper.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. using PTMedicalInsurance.Variables;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. namespace PTMedicalInsurance.Common
  10. {
  11. public class ProgressDialog : Form
  12. {
  13. private ProgressBar progressBar1;
  14. private Label labelStatus;
  15. private Button cancelButton;
  16. BackgroundWorker _backgroundWorker;
  17. private int maximum;
  18. public ProgressDialog()
  19. {
  20. Init();
  21. }
  22. public ProgressDialog(BackgroundWorker backgroundWorker)
  23. {
  24. Init();
  25. _backgroundWorker = backgroundWorker;
  26. }
  27. private void Init()
  28. {
  29. Application.EnableVisualStyles();
  30. this.Text = "正在查询...";
  31. this.StartPosition = FormStartPosition.CenterParent;
  32. this.FormBorderStyle = FormBorderStyle.FixedDialog;
  33. this.MaximizeBox = false;
  34. this.MinimizeBox = false;
  35. this.ShowInTaskbar = false;
  36. this.TopMost = true; // 确保进度条始终在最前面
  37. this.CenterToScreen();
  38. progressBar1 = new ProgressBar
  39. {
  40. Location = new System.Drawing.Point(12, 12),
  41. Size = new System.Drawing.Size(260, 23)
  42. };
  43. progressBar1.Style = ProgressBarStyle.Continuous;
  44. //progressBar1.Style = ProgressBarStyle.Marquee;
  45. //progressBar1.MarqueeAnimationSpeed = 50;
  46. Controls.Add(progressBar1);
  47. labelStatus = new Label
  48. {
  49. Location = new System.Drawing.Point(12, 41),
  50. Size = new System.Drawing.Size(260, 23)
  51. };
  52. Controls.Add(labelStatus);
  53. //// 初始化取消按钮
  54. //cancelButton = new Button
  55. //{
  56. // Text = "取消",
  57. // Location = new System.Drawing.Point(197, 41), // 设置适当的位置
  58. // Size = new System.Drawing.Size(75, 23) // 设置按钮大小
  59. //};
  60. //cancelButton.Click += CancelButton_Click; // 添加点击事件处理程序
  61. //Controls.Add(cancelButton);
  62. // 初始化取消按钮
  63. cancelButton = new Button
  64. {
  65. Text = "取消",
  66. Location = new System.Drawing.Point(197, 60), // 修改Y坐标以避免与labelStatus重叠
  67. Size = new System.Drawing.Size(75, 23) // 设置按钮大小
  68. };
  69. cancelButton.Click += CancelButton_Click; // 添加点击事件处理程序
  70. Controls.Add(cancelButton);
  71. // 设置默认样式
  72. SetStyle(ControlStyles.ResizeRedraw, true);
  73. ClientSize = new System.Drawing.Size(284, 100);
  74. }
  75. // 允许外部设置进度条的值
  76. public int ProgressValue
  77. {
  78. set { if (InvokeRequired) Invoke(new Action(() => progressBar1.Value = value)); else progressBar1.Value = value; }
  79. }
  80. public void UpdateProgress(int progress)
  81. {
  82. //if (progressBar1.InvokeRequired)
  83. //{
  84. // progressBar1.Invoke(new Action<int>(UpdateProgress), progress);
  85. //}
  86. //else
  87. //{
  88. // progressBar1.Value = progress;
  89. // //这个有点糊涂了,这个进度条显示总是少一个
  90. // labelStatus.Text = $"已完成 {progress}/{maximum}";
  91. //}
  92. this.Invoke((MethodInvoker)delegate
  93. {
  94. progressBar1.Value = progress;
  95. //这个有点糊涂了,这个进度条显示总是少一个
  96. labelStatus.Text = $"已完成 {progress}/{maximum}";
  97. ///在Windows Forms应用程序中,控件的更新通常是由操作系统消息循环处理的。当你修改一个控件的属性(如 Text 或 Value),
  98. ///这些更改并不会立即反映在界面上,而是会被放入队列等待下一个合适的时机进行绘制。这是因为直接更新控件属性并不会强制执行重绘操作,
  99. ///系统可能会批量处理多个更新以提高效率。
  100. ///使用 Refresh() 方法 调用控件的 Refresh() 方法会强制该控件立即重绘自身。这包括清除控件并重新绘制其所有内容
  101. if (progress == maximum)
  102. {
  103. progressBar1.Refresh();
  104. labelStatus.Refresh();
  105. }
  106. });
  107. }
  108. public void SetProgress(int max)
  109. {
  110. maximum = max;
  111. progressBar1.Maximum = maximum;
  112. }
  113. // 允许外部设置状态文本
  114. public string StatusText
  115. {
  116. set { if (InvokeRequired) Invoke(new Action(() => labelStatus.Text = value)); else labelStatus.Text = value; }
  117. }
  118. //异步展示
  119. public async void ShowAsync()
  120. {
  121. await Task.Run(() => progressBar1.Show());
  122. }
  123. private void CancelButton_Click(object sender, EventArgs e)
  124. {
  125. // 这里可以放置取消操作的逻辑
  126. // 比如通知BackgroundWorker取消工作
  127. if (_backgroundWorker != null && _backgroundWorker.WorkerSupportsCancellation)
  128. {
  129. _backgroundWorker.CancelAsync();
  130. }
  131. this.Close(); // 关闭对话框
  132. }
  133. }
  134. public class DataLoader : IDisposable
  135. {
  136. private BackgroundWorker _backgroundWorker = new BackgroundWorker();
  137. public delegate int MyFunc<T1>(out T1 err,ProgressCallback progressCallback);
  138. private MyFunc<string> _queryExportDataAction;
  139. private ProgressDialog progressDialog ;
  140. private Form mainForm;
  141. // 定义进度回调委托
  142. public delegate void ProgressCallback(int progress);
  143. public DataLoader(MyFunc<string> queryExportDataAction,Form frm)
  144. {
  145. mainForm = frm;
  146. _queryExportDataAction = queryExportDataAction ?? throw new ArgumentNullException(nameof(queryExportDataAction));
  147. // 配置 BackgroundWorker
  148. _backgroundWorker.WorkerReportsProgress = true;
  149. _backgroundWorker.WorkerSupportsCancellation = true;
  150. _backgroundWorker.DoWork += BackgroundWorker_DoWork;
  151. _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
  152. _backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
  153. }
  154. public void StartQueryExportData(int total, Action<int, string> onCompleted)
  155. {
  156. progressDialog = new ProgressDialog(_backgroundWorker);
  157. if (mainForm == null)
  158. {
  159. progressDialog.Show();
  160. }
  161. else
  162. {
  163. progressDialog.Show(mainForm);
  164. }
  165. if (_backgroundWorker.IsBusy) return;
  166. this._onCompleted = onCompleted;
  167. _backgroundWorker.RunWorkerAsync(total);
  168. }
  169. private Action<int, string> _onCompleted;
  170. private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  171. {
  172. // 调用传入的方法
  173. string errMsg = "";
  174. int total = (int)e.Argument; // 获取传入的总项目数
  175. progressDialog.SetProgress(total);
  176. //注意,如果_queryExportDataAction 事件里需要更新UI 必须使用 Control.Invoke 或 Control.BeginInvoke。否则会导致程序卡死
  177. ///类似这样:this.Invoke((MethodInvoker)delegate {labelProgress.Text = $"Progress: {progress}%"; });
  178. int result = _queryExportDataAction(out errMsg, (progress) =>
  179. {
  180. if (!_backgroundWorker.CancellationPending)
  181. {
  182. _backgroundWorker.ReportProgress(progress);
  183. }
  184. else
  185. {
  186. // 如果用户请求了取消,则跳出循环或采取其他措施
  187. // 这个异常处理查询下
  188. throw new OperationCanceledException();
  189. }
  190. });
  191. e.Result = Tuple.Create(result, errMsg);
  192. }
  193. private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  194. {
  195. if (!_backgroundWorker.CancellationPending)
  196. {
  197. System.Threading.Thread.Sleep(1000);
  198. }
  199. progressDialog.Close();
  200. if (e.Error != null)
  201. {
  202. // 处理错误
  203. MessageBox.Show($"An error occurred: {e.Error.Message}");
  204. }
  205. else if (e.Cancelled)
  206. {
  207. // 处理取消的情况
  208. MessageBox.Show("Operation was cancelled.");
  209. }
  210. else
  211. {
  212. var resultTuple = (Tuple<int, string>)e.Result;
  213. int result = resultTuple.Item1;
  214. string errMsg = resultTuple.Item2;
  215. // 调用回调函数,传递结果和错误信息
  216. _onCompleted?.Invoke(result, errMsg);
  217. }
  218. Dispose();
  219. }
  220. private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
  221. {
  222. progressDialog.UpdateProgress(e.ProgressPercentage );
  223. }
  224. public void Dispose()
  225. {
  226. _backgroundWorker.Dispose();
  227. progressDialog.Dispose();
  228. }
  229. }
  230. }