最基礎的 Windows Forms 程式:一個表單、兩個按鈕、點擊彈出訊息。本文提供 Form1.cs 完整代碼,展示標準專案結構、事件訂閱、訊息框呼叫。
using System;
using System.Windows.Forms;
namespace FormsTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // 初始化設計器產生的 UI
}
// button1 點擊事件處理
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("你點擊了左邊的 button1 按鈕。");
}
// button2 點擊事件處理
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("你點擊了右邊的 button2 按鈕。");
}
}
}
// 控制項宣告
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
// InitializeComponent 片段
this.button1 = new System.Windows.Forms.Button();
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.Click += new System.EventHandler(this.button1_Click);
this.button2 = new System.Windows.Forms.Button();
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.Click += new System.EventHandler(this.button2_Click);
// 加入表單控制項集合
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Main() ↓ Application.Run(new Form1()) ↓ Form1 建構函數 ↓ InitializeComponent() ├─ new Button() × 2 ├─ 設定 Location/Size/Text/TabIndex ├─ button.Click += Handler └─ Controls.Add(button) ↓ Form1 顯示 (Show) ↓ Application.Run 進入訊息迴圈 ↓ 使用者點擊 button1 ↓ Windows 訊息 → Click 事件 → button1_Click() ↓ MessageBox.Show(...) ↓ 使用者關閉 MessageBox ↓ 繼續訊息迴圈...
Form1.cs + Form1.Designer.cs = 完整 Form1+= new EventHandler(...),開發者只實作 HandlercontrolName_EventName (如 button1_Click)此範例展示了 Windows Forms 開發的最小閉環:設計器拖拉控制項 → 雙擊產生事件 Handler → 撰寫業務代碼 → F5 執行。掌握此模式,即可進入 WinForms 視覺化開發世界。