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

C# GUI 開發入門:溫度轉換器完整實作 (System.Windows.Forms)

     編輯:關於C#

本文以攝氏/華氏溫度轉換器為例,示範 .NET Framework 早期 (System.Windows.Forms 命名空間) 的 GUI 程式設計基本流程:建立表單、配置控制項、事件繫結、輸入驗證與單位轉換邏輯。雖然現代開發多用 .NET Core/5+ 的 WinForms/WPF,但核心觀念相通。

完整程式碼 (TempConverter.cs)

using System;
using System.Windows.Forms;
using System.Drawing;

public class TempConverter : Form
{
    // 控制項宣告
    private readonly Label lblC = new Label();
    private readonly Label lblF = new Label();
    private readonly TextBox txtC = new TextBox();
    private readonly TextBox txtF = new TextBox();
    private readonly Button btnCtoF = new Button();
    private readonly Button btnFtoC = new Button();

    public TempConverter()
    {
        // 表單屬性
        Text = "℃→℉ / ℉→℃ 轉換器";
        ClientSize = new Size(260, 120);
        FormBorderStyle = FormBorderStyle.FixedDialog;
        MaximizeBox = false;
        StartPosition = FormStartPosition.CenterScreen;

        // 攝氏區
        txtC.Location = new Point(10, 10);
        txtC.Size = new Size(80, 25);
        txtC.TabIndex = 0;

        lblC.Text = "℃";
        lblC.Location = new Point(100, 12);
        lblC.AutoSize = true;

        // 華氏區
        txtF.Location = new Point(10, 45);
        txtF.Size = new Size(80, 25);
        txtF.TabIndex = 1;

        lblF.Text = "℉";
        lblF.Location = new Point(100, 47);
        lblF.AutoSize = true;

        // 按鈕
        btnCtoF.Text = "℃ → ℉";
        btnCtoF.Location = new Point(130, 10);
        btnCtoF.Size = new Size(100, 30);
        btnCtoF.TabIndex = 2;
        btnCtoF.Click += BtnCtoF_Click;

        btnFtoC.Text = "℉ → ℃";
        btnFtoC.Location = new Point(130, 45);
        btnFtoC.Size = new Size(100, 30);
        btnFtoC.TabIndex = 3;
        btnFtoC.Click += BtnFtoC_Click;

        // 加入控制項
        Controls.AddRange(new Control[] { txtC, lblC, txtF, lblF, btnCtoF, btnFtoC });

        // 預設焦點
        txtC.Focus();
    }

    private void BtnCtoF_Click(object sender, EventArgs e)
    {
        if (!double.TryParse(txtC.Text, out double c))
        {
            MessageBox.Show("請輸入有效的數字", "輸入錯誤");
            txtC.Clear(); txtF.Clear();
            txtC.Focus();
            return;
        }

        double f = c * 1.8 + 32;
        txtF.Text = f.ToString("F2"); // 保留兩位小數
        txtF.Focus();
        txtF.SelectAll();
    }

    private void BtnFtoC_Click(object sender, EventArgs e)
    {
        if (!double.TryParse(txtF.Text, out double f))
        {
            MessageBox.Show("請輸入有效的數字", "輸入錯誤");
            txtC.Clear(); txtF.Clear();
            txtF.Focus();
            return;
        }

        double c = (f - 32) / 1.8;
        txtC.Text = c.ToString("F2");
        txtC.Focus();
        txtC.SelectAll();
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new TempConverter());
    }
}

編譯與執行

# .NET Framework (csc.exe)
csc /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll TempConverter.cs

# .NET Core / .NET 5+ (SDK)
dotnet new winforms -o TempConv
# 將 Program.cs 替換為上述程式碼
dotnet run

關鍵觀念解析

觀念說明
表單繼承自訂類別繼承 Form,在建構函式初始化 UI
控制項實例化new Button() 等,設定 Location/Size/Text
事件繫結btn.Click += Handler 或設計器自動產生
版面配置絕對座標 (Location);現代建議用 TableLayoutPanel/FlowLayoutPanel
輸入驗證double.TryParse 避免例外,給予使用者友善提示
焦點管理Focus()、SelectAll() 提升使用體驗
應用程式進入點Application.Run(new Form()) 啟動訊息迴圈

現代化改良建議

  • 使用 Data Binding:將 txtC.Text、txtF.Text 繫結至 ViewModel 屬性,轉換邏輯移至 set 存取子。
  • 加入 鍵盤快捷鍵:Enter 觸發轉換、Escape 清空。
  • 支援 Kelvin (K)、Rankine (°R) 等更多單位,下拉選單切換。
  • 採用 MVP/MVVM 模式分離 UI 與商業邏輯,便於單元測試。
  • 高 DPI 支援:專案屬性勾選 Enable Windows Forms High DPI,或 Application.SetHighDpiMode(HighDpiMode.PerMonitorV2)。

常見錯誤與除錯

  • 控制項不顯示:忘記 Controls.Add() 或座標超出 ClientSize。
  • 事件不觸發:建構函式中 InitializeComponent() 之後才繫結事件,或 Handler 簽名錯誤。
  • 中文亂碼:原始檔儲存為 UTF-8 with BOM,或專案設定 LangVersion。
  • 跨執行緒存取 UI:背景執行緒需用 Invoke / BeginInvoke 回主執行緒更新控制項。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved