首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Windows Forms 經典入門範例:雙按鈕點擊彈出訊息框完整代碼

     編輯:關於C語言

前言

最基礎的 Windows Forms 程式:一個表單、兩個按鈕、點擊彈出訊息。本文提供 Form1.cs 完整代碼,展示標準專案結構、事件訂閱、訊息框呼叫。

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 按鈕。");
        }
    }
}

對應的 Designer.cs 關鍵片段 (自動產生)

// 控制項宣告
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);

Program.cs 入口 (標準模板)

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
  ↓
繼續訊息迴圈...

核心知識點

  1. Partial Class:Form1.cs + Form1.Designer.cs = 完整 Form1
  2. 事件訂閱:設計器產生 += new EventHandler(...),開發者只實作 Handler
  3. MessageBox.Show:模態對話框,阻塞直到使用者關閉
  4. 命名慣例:controlName_EventName (如 button1_Click)
  5. 零手工 UI 代碼:所有控制項建立、屬性設定、版面配置由設計器完成

總結

此範例展示了 Windows Forms 開發的最小閉環:設計器拖拉控制項 → 雙擊產生事件 Handler → 撰寫業務代碼 → F5 執行。掌握此模式,即可進入 WinForms 視覺化開發世界。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved