using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            switchButton(false);
            this.backgroundWorker1.RunWorkerAsync(100);
        }

        protected void switchButton(Boolean ok)
        {
            this.button1.Enabled = ok;
            this.button2.Enabled = ok == false;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.CancelAsync();
            switchButton(true);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show(this, "button clicked");
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                if (e.Cancel = bw.CancellationPending)
                {
                    return;
                }
                else
                {
                    Thread.Sleep(100);
                    bw.ReportProgress(1);
                }
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Increment(e.ProgressPercentage);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == false)
            {
                MessageBox.Show(this,"Finished");
            }
            this.progressBar1.Value = 0;
            switchButton(true);
        }

    }
}