看範例學C#-07 Windows Form 表單的啟動順序

  • 22431
  • 0
  • C#
  • 2011-10-04

Windows Form 表單的啟動順序

我們在程式執行時會先去執行Program.cs 裡面 Main這一段去呼叫第一個啟動的form

這範例的啟動表單就叫BaseForm

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new BaseForm());
}

接著會執行表單內的這一段 public 加上表單名稱,從

InitializeComponent();下面 是我自己加的,目的是設定這四個Form事件所對應的副程式

public BaseForm()
{
    InitializeComponent();
    Load += new System.EventHandler(this.BaseForm_Load);
    Shown += new System.EventHandler(this.BaseForm_Shown);
    Closing += new CancelEventHandler(BaseForm_Closing); //設定要觸發的事件
    Closed += new EventHandler(BaseForm_Closed);
}

這個範例可以看出Windows Form的啟動順序

如果有需要把Form一啟動就隱藏,就要在Form.Shown事件加上this.Hide();

而不是加在Form.Load 事件裡,因為在load時隱藏到shown的時候他又會把表單顯示出來

有時候會需要在右上 按叉叉 關閉程式的時候 出現確認關閉的視窗按 yes就關閉,no就不關閉

就是要把程式寫在Form.Closing 事件內,因為要在表單關閉前提示,如下

void BaseForm_Closing(object sender, CancelEventArgs e)
{
    MessageBox.Show("Closing event\n");
    DialogResult dr = MessageBox.Show("確定要關閉程式嗎?",
        "Closing event!", MessageBoxButtons.YesNo);
    if (dr == DialogResult.No)
        e.Cancel = true;//取消離開
    else
        e.Cancel = false;
}

 

Form.Load 事件

發生在表單第一次顯示之前。

Form.Shown 事件

只有當第一次顯示表單時,才會引發 Shown 事件

Form.Closing 事件

發生於表單正在關閉時。

Form.Closed 事件

發生於表單已關閉時。

 

以下為程式碼及註解

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 ex07
{
    public partial class BaseForm : Form
    {
        public BaseForm()
        {
            InitializeComponent();
            Load += new System.EventHandler(this.BaseForm_Load);
            Shown += new System.EventHandler(this.BaseForm_Shown);
            Closing += new CancelEventHandler(BaseForm_Closing); //設定要觸發的事件
            Closed += new EventHandler(BaseForm_Closed);
         }
        #region Form events
        private void BaseForm_Load(object sender, EventArgs e)
        {
                MessageBox.Show("Load event\n");
        }
        private void BaseForm_Closed(object sender, System.EventArgs e)
        {
            MessageBox.Show("Closed event\n");
        }
        void BaseForm_Closing(object sender, CancelEventArgs e)
        {
            MessageBox.Show("Closing event\n");
            DialogResult dr = MessageBox.Show("確定要關閉程式嗎?",
                "Closing event!", MessageBoxButtons.YesNo);
            if (dr == DialogResult.No)
                e.Cancel = true;//取消離開
            else
                e.Cancel = false;
        }
        private void BaseForm_Shown(object sender, EventArgs e)
        {
            MessageBox.Show("Shown event\n");
            //this.Hide(); //隱藏表單要在load 之後會接著做shown,所以表單要隱藏要放在shown
        }
        #endregion
    }
}

ex07.rar


如有錯誤 歡迎指正