在控制台應用程式中Main函數是程式的進入點。同樣地,在Windows表單應用程式中,Main函數也是程式進入點。這可以通過調試看出來,方法如下所示。
(1)開啟或建立一個Windows表單應用程式,如前面的FormsTest應用程式。
(2)單擊“調試”|“逐句調試”命令,也可以按快速鍵F11。可以看到,程式會跳轉到Program.cs檔案。指示啟動並執行黃色箭頭指向Main函數的起始位置。
(3)繼續按F11鍵,直到運行箭頭移動到函數最後一句,代碼如下所示。
Application.Run(new Form1());
該語句表示,開始應用程式訊息迴圈。其參數new Form1()用於執行個體化Form1類,這個類就是表單類Form的一個衍生類別。對介面設計和事件的處理代碼都放在了Form1類中。
(4)再按F11鍵,程式運行至Form1.Designer.cs檔案。該檔案中存放了有關介面設計的初始化內容,如控制項、控制項布局、控制項事件(或者叫委託)的處理常式等,代碼如下。
/* Form1.Designer.cs檔案 */
namespace FormsTest
{
partial class Form1
{
/// <summary>
/// 必需的設計器變數
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的資源
/// </summary>
/// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。
</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 表單設計器產生的程式碼
/// <summary>
/// 設計器支援所需的方法 - 不要
/// 使用代碼編輯器修改此方法的內容
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(35, 211);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(167, 211);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}
一般來說,程式員不必直接編寫上面的代碼。因為Form類會自動處理這些事情。前面講過,這些事情包括了控制項、控制項布局、控制項事件的處理常式等。程式員也不必關心事件何時會被調用,何時結束。程式員所需要做的就是編寫響應事件的具體代碼。