天天看點

在新線程中打開視窗C#例子

 在新線程中打開視窗

 using System.Threading;//引用此命名

  //建立代理。

  private Form6 myProcessBar = null; //彈出的子窗體(用于顯示進度條)

  private delegate bool IncreaseHandle(int nValue,string vinfo);//代理建立

  private IncreaseHandle myIncrease = null;//聲明代理,用于後面的執行個體化代理

  private int vMax = 100; //用于執行個體化進度條,可以根據自己的需要,自己改變

  private void button1_Click(object sender, EventArgs e)

  {

      Thread thdSub = new Thread(new ThreadStart(ThreadFun));

      thdSub.Start();

  }

  private void ThreadFun()

  {

      MethodInvoker mi = new MethodInvoker(ShowProcessBar);

      this.BeginInvoke(mi);

      Thread.Sleep(100);

      object objReturn = null;

      for (int i = 0; i < vMax; i++)

      {

          objReturn = this.Invoke(this.myIncrease, new object[] { 2, i.ToString() + "\r\n" });

          Thread.Sleep(50);

      }

  }

  private void ShowProcessBar()

  {

      myProcessBar = new Form6(vMax);

      myIncrease = new IncreaseHandle(myProcessBar.Increase);

      myProcessBar.ShowDialog();

      myProcessBar = null;

  }

Form code        

public Form6(int vMax)

{

    InitializeComponent();

    this.progressBar1.Maximum = vMax;

}

public bool Increase(int nValue,string nInfo)

{

    if (nValue > 0)

    {

        if (progressBar1.Value + nValue < progressBar1.Maximum)

        {

            progressBar1.Value += nValue;

            this.textBox1.AppendText(nInfo);

            Application.DoEvents();

            progressBar1.Update();

            progressBar1.Refresh();

            this.textBox1.Update();

            this.textBox1.Refresh();

            return true;

        }

        else

        {

            progressBar1.Value = progressBar1.Maximum;

            this.textBox1.AppendText(nInfo);

            //this.Close();//執行完之後,自動關閉子窗體

            return false;

        }

    }

    return false;

}