星期四, 7月 17, 2014

[C#] 關閉全部的 Form

論壇問題,原本問題是要根據輸入的數值來決定關閉多少已開啟的 Form,換句話說來練習一下,關閉全部已開啟的 Form

OpenForms 作法
namespace CloseAllForm
{
    public partial class OpenForms : Form
    {
        public OpenForms()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {

                FormShow demo = new FormShow();

                int x = 10 * i;
                int y = 20 * i;
                demo.Location = new Point(x, y);

                string FormInfo = string.Format("Form{0}", i);
                demo.Text = FormInfo;
                demo.Name = FormInfo;

                demo.Show();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            List<Form> FormClose = Application.OpenForms.OfType<Form>().ToList();
            foreach (Form item in FormClose)
            {
                if (Form.ActiveForm == item) continue;
                item.Close();
            }
        }
    }
}

Owner 作法
namespace CloseAllForm
{
   public partial class Owner : Form
    {
        public Owner()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {

                FormShow demo = new FormShow();

                int x = 10 * i;
                int y = 20 * i;
                demo.Location = new Point(x, y);

                string FormInfo = string.Format("Form{0}", i);
                demo.Text = FormInfo;
                demo.Name = FormInfo;
                // btnOpen 在 OpenForms 和 Owner 作法只有差異在這一段
                demo.Owner = this;

                demo.Show();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            // 方法一
            foreach (Form item in this.OwnedForms)
            {
                item.Close();
            }

            // 方法二
            int FormCount = this.OwnedForms.Length;
            for (int i = 0; i < FormCount; i++)
            {
                this.OwnedForms[0].Close();
            }
        }
    }
}

沒有留言:

張貼留言