| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace PTMedicalInsurance.Common
- {
- public class ProgressHelper
- {
- private readonly BackgroundWorker _backgroundWorker;
- private readonly System.Windows.Forms.ProgressBar _progressBar;
- private Action<int> _updateProgressAction;
- public ProgressHelper(System.Windows.Forms.ProgressBar progressBar)
- {
- _progressBar = progressBar;
- _backgroundWorker = new BackgroundWorker
- {
- WorkerReportsProgress = true,
- WorkerSupportsCancellation = true
- };
- _backgroundWorker.DoWork += BackgroundWorker_DoWork;
- _backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
- _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
- }
- // 启动进度条,传入要执行的工作方法和是否需要显示具体进度
- public void Start(Action workMethod, bool showSpecificProgress = false)
- {
- if (_backgroundWorker.IsBusy) return;
- _progressBar.Style = showSpecificProgress ? ProgressBarStyle.Continuous : ProgressBarStyle.Marquee;
- _progressBar.Value = 0;
- _backgroundWorker.RunWorkerAsync(new { WorkMethod = workMethod, ShowSpecificProgress = showSpecificProgress });
- }
- // 更新进度条(仅当显示具体进度时)
- public void UpdateProgress(int percentage)
- {
- if (_backgroundWorker.CancellationPending) return;
- if (_updateProgressAction != null)
- {
- _updateProgressAction(percentage);
- }
- }
- // 取消正在进行的操作
- public void Cancel()
- {
- if (!_backgroundWorker.CancellationPending)
- {
- _backgroundWorker.CancelAsync();
- }
- }
- private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
- {
- var parameters = (dynamic)e.Argument;
- var workMethod = parameters.WorkMethod;
- var showSpecificProgress = parameters.ShowSpecificProgress;
- try
- {
- if (showSpecificProgress)
- {
- _updateProgressAction = progress => ((BackgroundWorker)sender).ReportProgress(progress);
- }
- workMethod(); // 执行传入的工作方法
- }
- catch (Exception ex)
- {
- MessageBox.Show($"An error occurred: {ex.Message}");
- e.Cancel = true;
- }
- finally
- {
- _updateProgressAction = null;
- }
- }
- private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- _progressBar.Value = e.ProgressPercentage;
- }
- private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- if (!e.Cancelled && (e.Error != null))
- {
- _progressBar.Value = 0;
- _progressBar.Style = ProgressBarStyle.Continuous;
- }
- }
- }
- public class OverlayProgressBarManager
- {
- private ProgressBar progressBar;
- private Form form;
- private Form frm = new Form();
- public OverlayProgressBarManager(Form form)
- {
- this.form = form;
-
- progressBar = new ProgressBar();
- progressBar.Style = ProgressBarStyle.Marquee; // Set the style to Marquee.
- progressBar.MarqueeAnimationSpeed = 30; // Adjust speed of animation.
- progressBar.Visible = false;
- progressBar.Anchor = AnchorStyles.None; // Do not anchor to any edge.
- //form.Controls.Add(progressBar);
- //form.Resize += OnFormResize; // Handle form resize event.
-
- frm.Width = 2000;
- frm.Left = 20;
- frm.Height = 200;
- frm.Controls.Add(progressBar);
- frm.Resize += OnFormResize; // Handle form resize event.
- CenterProgressBar(); // Initially center the progress bar.
- }
- private void OnFormResize(object sender, EventArgs e)
- {
- CenterProgressBar();
- }
- private void CenterProgressBar()
- {
- if (progressBar.Parent != null && !progressBar.Parent.IsDisposed)
- {
- progressBar.Left = (progressBar.Parent.ClientSize.Width - progressBar.Width) / 2;
- progressBar.Top = (progressBar.Parent.ClientSize.Height - progressBar.Height) / 2;
- }
- }
- public void Start()
- {
- progressBar.Visible = true;
- progressBar.MarqueeAnimationSpeed = 30; // Restart the animation.
- CenterProgressBar(); // Ensure it's centered when started.
- frm.ShowDialog();
- }
- public void Stop()
- {
- //progressBar.MarqueeAnimationSpeed = 0; // Stop the animation.
- //progressBar.Visible = false;
- frm.Close();
- }
- }
- public class ProgressDialog : Form
- {
- private ProgressBar progressBar1;
- private Label labelStatus;
- public ProgressDialog()
- {
- Application.EnableVisualStyles();
- this.Text = "正在查询...";
- this.StartPosition = FormStartPosition.CenterParent;
- this.FormBorderStyle = FormBorderStyle.FixedDialog;
- this.MaximizeBox = false;
- this.MinimizeBox = false;
- this.ShowInTaskbar = false;
- this.TopMost = true; // 确保进度条始终在最前面
- this.CenterToScreen();
- progressBar1 = new ProgressBar
- {
- Location = new System.Drawing.Point(12, 12),
- Size = new System.Drawing.Size(260, 23)
- };
- progressBar1.Style = ProgressBarStyle.Marquee;
- progressBar1.MarqueeAnimationSpeed = 50;
- Controls.Add(progressBar1);
- labelStatus = new Label
- {
- Location = new System.Drawing.Point(12, 41),
- Size = new System.Drawing.Size(260, 23)
- };
- Controls.Add(labelStatus);
- // 设置默认样式
- SetStyle(ControlStyles.ResizeRedraw, true);
- ClientSize = new System.Drawing.Size(284, 75);
- }
- // 允许外部设置进度条的值
- public int ProgressValue
- {
- set { if (InvokeRequired) Invoke(new Action(() => progressBar1.Value = value)); else progressBar1.Value = value; }
- }
- // 允许外部设置状态文本
- public string StatusText
- {
- set { if (InvokeRequired) Invoke(new Action(() => labelStatus.Text = value)); else labelStatus.Text = value; }
- }
- //异步展示
- public async void ShowAsync()
- {
- await Task.Run(() => progressBar1.Show());
- }
- }
- //public class DataLoader
- //{
- // private ProgressDialog progressDialog;
- // public DataLoader(Func<Task> loadDataAsync)
- // {
- // this.loadDataAsync = loadDataAsync ?? throw new ArgumentNullException(nameof(loadDataAsync));
- // }
- // private readonly Func<Task> loadDataAsync;
- // // 执行数据加载操作
- // public async Task ExecuteLoadOperation()
- // {
- // progressDialog = new ProgressDialog();
- // // 使用 BeginInvoke 确保 Show 在正确的线程上调用
- // if (progressDialog.InvokeRequired)
- // {
- // progressDialog.BeginInvoke(new Action(() => progressDialog.ShowDialog()));
- // }
- // else
- // {
- // progressDialog.Show();
- // }
- // try
- // {
- // // 执行传入的数据加载操作
- // await loadDataAsync();
- // progressDialog.DialogResult = DialogResult.OK;
- // }
- // finally
- // {
- // // 确保即使发生异常也会关闭进度框
- // CloseProgressDialog();
- // }
- // }
- // private void CloseProgressDialog()
- // {
- // if (progressDialog != null && !progressDialog.IsDisposed)
- // {
- // // 使用 BeginInvoke 确保 Close 在正确的线程上调用
- // if (progressDialog.InvokeRequired)
- // {
- // progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
- // }
- // else
- // {
- // progressDialog.Close();
- // }
- // }
- // }
- ////}
- public class DataLoader : IDisposable
- {
- private readonly BackgroundWorker _backgroundWorker = new BackgroundWorker();
- public delegate int MyFunc<T1>(out T1 err);
- private MyFunc<string> _queryExportDataAction;
- private ProgressDialog progressDialog = new ProgressDialog();
- private Form mainForm;
-
- public DataLoader(MyFunc<string> queryExportDataAction,Form frm)
- {
- mainForm = frm;
- _queryExportDataAction = queryExportDataAction ?? throw new ArgumentNullException(nameof(queryExportDataAction));
-
- // 配置 BackgroundWorker
- _backgroundWorker.WorkerReportsProgress = true;
- _backgroundWorker.WorkerSupportsCancellation = true;
- _backgroundWorker.DoWork += BackgroundWorker_DoWork;
- _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
- }
- public void StartQueryExportData(Action<int, string> onCompleted)
- {
- if (mainForm == null)
- {
- progressDialog.Show();
- }
- else
- {
- progressDialog.Show(mainForm);
- }
- if (_backgroundWorker.IsBusy) return;
- this._onCompleted = onCompleted;
- _backgroundWorker.RunWorkerAsync();
- }
- private Action<int, string> _onCompleted;
- private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
- {
- // 调用传入的方法
- string errMsg = "";
- int result = _queryExportDataAction(out errMsg);
- e.Result = Tuple.Create(result, errMsg);
- }
- private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- progressDialog.Close();
- if (e.Error != null)
- {
- // 处理错误
- MessageBox.Show($"An error occurred: {e.Error.Message}");
- }
- else if (e.Cancelled)
- {
- // 处理取消的情况
- MessageBox.Show("Operation was cancelled.");
- }
- else
- {
- var resultTuple = (Tuple<int, string>)e.Result;
- int result = resultTuple.Item1;
- string errMsg = resultTuple.Item2;
- // 调用回调函数,传递结果和错误信息
- _onCompleted?.Invoke(result, errMsg);
- }
-
- }
- public void Dispose()
- {
- _backgroundWorker.Dispose();
- }
- }
- }
|