public partial class MainWindow : Window {
System.ComponentModel.BackgroundWorker Worker;
public MainWindow() {
InitializeComponent();
stopBtn.IsEnabled = false;
}
private void startBtn_click(object sender, RoutedEventArgs e) {
startBtn.IsEnabled = false;
stopBtn.IsEnabled = true;
progbar1.Value = 0;
Worker = new System.ComponentModel.BackgroundWorker();
Worker.DoWork += new System.ComponentModel.DoWorkEventHandler(Worker_DoWork);
Worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(Worker_ProgressChanged);
Worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
Worker.WorkerReportsProgress = true;
Worker.WorkerSupportsCancellation = true;
Worker.RunWorkerAsync();
}
private void Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) {
startBtn.IsEnabled = true;
stopBtn.IsEnabled = false;
if (progbar1.Value == progbar1.Maximum) {
MessageBox.Show("完了");
}
else {
MessageBox.Show("キャンセル");
}
}
private void Worker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) {
progbar1.Value = e.ProgressPercentage;
}
private void Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
for (int value = 1; value <= 100; value++) {
if (Worker.CancellationPending) break;
Worker.ReportProgress(value);
System.Threading.Thread.Sleep(100);
}
}
private void stopBtn_Click(object sender, RoutedEventArgs e) {
Worker.CancelAsync();
}
}