主窗口代碼less
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ProgressbarTest { public partial class Form1 : MaterialSkin.Controls.MaterialForm { public Form1() { InitializeComponent(); Bkg_ClaculateStatus.WorkerReportsProgress = true; Bkg_ClaculateStatus.WorkerSupportsCancellation = true; Bkg_ClaculateStatus.DoWork += DoWork_Handler; Bkg_ClaculateStatus.ProgressChanged += ProcessChanged_Handler; Bkg_ClaculateStatus.RunWorkerCompleted += RunWorkerCompleted_Handler; } ProgressBar progressBar= new ProgressBar(); private void materialFlatButton1_Click(object sender, EventArgs e) { if (!Bkg_ClaculateStatus.IsBusy) { Bkg_ClaculateStatus.RunWorkerAsync(); progressBar.StartPosition = FormStartPosition.CenterParent; progressBar.ShowDialog(); } } /// <summary> /// Use less variables to implement Fibonacci /// </summary> /// <param name="n"></param> /// <returns></returns> static int Fn2(int n) { if (n <= 0) { throw new ArgumentOutOfRangeException(); } int a = 1; int b = 1; for (int i = 3; i <= n; i++) { b = checked(a + b); // when n>46 memory will overflow a = b - a; } return b; } private void DoWork_Handler(object sender, DoWorkEventArgs args) { BackgroundWorker worker= sender as BackgroundWorker; for (int i = 1; i < 10; i++) { if (worker.CancellationPending) { args.Cancel = true; break; } else { worker.ReportProgress(i*10); Thread.Sleep(500); } } } private void ProcessChanged_Handler(object sender, ProgressChangedEventArgs e) { progressBar.SetValue(e.ProgressPercentage); } private void RunWorkerCompleted_Handler(object sender, RunWorkerCompletedEventArgs e) { progressBar.SetValue(0); this.progressBar.Close(); } } }
進度條窗口代碼this
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProgressbarTest { public partial class ProgressBar : MaterialSkin.Controls.MaterialForm { public ProgressBar() { InitializeComponent(); } public void SetValue(int value) { this.materialProgressBar1.Value = value; } } }