C# 等待窗體 利用timer設置窗體是否關閉

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

namespace Myproject
{
    public class WaitPlz
    {
        public Thread thread;
        public FormWait formwait;
        private bool finished;  //指示線程工作是否完成

        public bool has_finished()
        {
            return finished;
        }

        public WaitPlz()
        {
            this.thread = null;
            this.formwait = null;
        }

        public void Show()
        {
            this.finished = false;
            this.thread = new Thread(ThreadFunction);
            thread.IsBackground = true;
            thread.Start();
        }

        private void ThreadFunction()
        {
            this.formwait = new FormWait(this);
            this.formwait.StartPosition = FormStartPosition.Manual;
            Point center = new Point(Application.OpenForms[0].Location.X + (Application.OpenForms[0].Width - formwait.Width) / 2, Application.OpenForms[0].Location.Y + (Application.OpenForms[0].Height + formwait.Height) / 2);
            this.formwait.Location = center;
            this.formwait.ShowDialog();
        }

        public void Close()
        {
            this.finished = true;
            this.thread.Join();
        }
    }
}


//////////////////////////////窗體類文件/////////////////////////////////////////////
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;

namespace Myproject
{
    public partial class FormWait : Form
    {
        private WaitPlz owner;   //窗體所屬線程
        public FormWait(WaitPlz owner)
        {
            InitializeComponent();
            this.owner = owner;
            timer1.Interval = 10;
            timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e) //timer 實時監測owner.has_finished()
        {              //如果船體所屬線程指示工作完成 則關閉窗體  
            if (this.owner.has_finished())
            {
                this.Close();
            }
        }

        private void FormWait_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Enabled = false;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章