理解 Windows Forms 應用程式的啟動流程、主迴圈機制、設計器生成程式碼與事件處理架構,是 WinForms 開發的基石。本文以完整範例解析每個關鍵環節。
using System;
using System.Windows.Forms;
namespace FormsApp
{
static class Program
{
///
/// 應用程式的主入口點
///
[STAThread] // 單執行緒單元模式,WinForms 必須
static void Main()
{
// 1. 啟用視覺樣式(讓控制項使用系統主題)
Application.EnableVisualStyles();
// 2. 設定文字渲染相容性(GDI+ vs GDI)
Application.SetCompatibleTextRenderingDefault(false);
// 3. 啟動訊息迴圈,執行主視窗
Application.Run(new MainForm());
}
}
}
using System;
using System.Windows.Forms;
namespace FormsApp
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent(); // 設計器生成的初始化
}
// 按鈕 1 點擊事件
private void btnLeft_Click(object sender, EventArgs e)
{
MessageBox.Show("你點擊了左側按鈕。");
}
// 按鈕 2 點擊事件
private void btnRight_Click(object sender, EventArgs e)
{
MessageBox.Show("你點擊了右側按鈕。");
}
}
}
namespace FormsApp
{
partial class MainForm
{
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.btnLeft = new Button();
this.btnRight = new Button();
this.SuspendLayout();
// btnLeft 設定
this.btnLeft.Location = new Point(35, 211);
this.btnLeft.Name = "btnLeft";
this.btnLeft.Size = new Size(75, 23);
this.btnLeft.TabIndex = 0;
this.btnLeft.Text = "左側按鈕";
this.btnLeft.Click += new EventHandler(this.btnLeft_Click);
// btnRight 設定
this.btnRight.Location = new Point(167, 211);
this.btnRight.Name = "btnRight";
this.btnRight.Size = new Size(75, 23);
this.btnRight.TabIndex = 1;
this.btnRight.Text = "右側按鈕";
this.btnRight.Click += new EventHandler(this.btnRight_Click);
// Form 設定
this.ClientSize = new Size(292, 273);
this.Controls.Add(this.btnRight);
this.Controls.Add(this.btnLeft);
this.Name = "MainForm";
this.Text = "範例程式";
this.ResumeLayout(false);
}
#endregion
private Button btnLeft;
private Button btnRight;
}
}
// 簡化版訊息迴圈邏輯
while (messageLoopRunning)
{
// 1. 取得訊息 (WM_PAINT, WM_MOUSEMOVE, WM_KEYDOWN, WM_TIMER, etc.)
GetMessage(out MSG msg);
// 2. 轉譯鍵盤訊息 (WM_KEYDOWN → WM_CHAR)
TranslateMessage(ref msg);
// 3. 分派訊息至對應視窗程序
DispatchMessage(ref msg); // 內部呼叫 WndProc → 觸發事件
// 4. 處理閒置工作
Application.Idle += ...;
}
// 設計器生成的事件訂閱
this.btnLeft.Click += new EventHandler(this.btnLeft_Click);
// 等同於手動訂閱
btnLeft.Click += (sender, e) => MessageBox.Show("左側按鈕");
// 事件模式:sender (事件來源) + EventArgs (事件資料)
// 自訂事件引數
public class CustomEventArgs : EventArgs
{
public string Message { get; set; }
public int Value { get; set; }
}
// 觸發事件的標準模式
protected virtual void OnCustomEvent(CustomEventArgs e)
{
CustomEvent?.Invoke(this, e);
}
掌握 WinForms 架構脈絡,能讓你從「會拖拉控制項」進階為「理解底層運作、能架構可維護應用」的專業開發者。