Windows Forms 程式雖以視覺化設計為主,但其代碼結構遵循嚴格規範:Program.cs 含 Main 入口,Form1.cs 為邏輯核心,Form1.Designer.cs 承載 UI 定義。本文完整呈現標準專案的三大檔案代碼與職責分工。
using System;
using System.Windows.Forms;
namespace FormsTest
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles(); // 系統視覺主題
Application.SetCompatibleTextRenderingDefault(false); // 文字繪製相容性
Application.Run(new Form1()); // 啟動訊息迴圈,顯示主表單
}
}
}
關鍵點:
static class Program:不可實例化,僅含靜態成員[STAThread]:COM 單執行緒單元模式,WinForms 強制要求Application.Run(form):阻塞直到 form.Close()using System;
using System.Windows.Forms;
namespace FormsTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // 呼叫設計器初始化
}
// 按鈕 1 點擊事件
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("你點擊了左邊的 button1 按鈕。");
}
// 按鈕 2 點擊事件
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("你點擊了右邊的 button2 按鈕。");
}
}
}
關鍵點:
partial class:與 Form1.Designer.cs 合併為完整類別InitializeComponent()private void ControlName_Event(object sender, EventArgs e) 命名慣例Main、無迴圈、無手動 UI 建立代碼namespace FormsTest
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) components.Dispose();
base.Dispose(disposing);
}
#region Windows Form Designer generated code
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;
}
}
| 檔案 | 職責 | 修改者 | 核心內容 |
|---|---|---|---|
| Program.cs | 應用程式啟動 | 開發者 (極少改動) | Main、STAThread、Application.Run |
| Form1.cs | 業務邏輯、事件處理 | 開發者 (主要工作區) | 建構函數、事件 Handler、自訂方法 |
| Form1.Designer.cs | UI 控制項樹、屬性、事件訂閱 | Visual Studio 設計器 (嚴禁手改) | InitializeComponent、控制項欄位、Dispose |