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

C# WinForms 打造簡易計算機:從介面佈局到邏輯實作完整教學

     編輯:關於C語言

計算機是初學 WinForms 的經典練習題。本文完整呈現從視覺化設計到事件驅動邏輯的實作過程,涵蓋數字鍵輸入、四則運算、清除功能,程式碼結構清晰,適合初學者理解事件處理與狀態管理。

1. 介面設計

在 Form 上拖放:

  • 一個 TextBox txtDisplay - 顯示輸入與結果,設 ReadOnly = true、靠右對齊
  • 數字鍵 0-9:Button btn0 ~ Button btn9
  • 運算鍵:btnAdd(+)、btnSub(-)、btnMul(*)、btnDiv(/)
  • 功能鍵:btnEqual(=)、btnClear(C)

建議採用 TableLayoutPanel 排版,固定按鈕大小與間距。

2. 核心變數設計

public partial class Form1 : Form
{
    private double _firstOperand = 0;   // 第一個運算元
    private string _currentOperator = ""; // 當前運算子 + - * /
    private bool _isNewInput = true;    // 標記是否開始新數字輸入

    public Form1() { InitializeComponent(); }
}

3. 數字鍵統一事件處理

將所有數字鍵的 Click 事件指向同一個處理函式:

private void NumberButton_Click(object sender, EventArgs e)
{
    var btn = (Button)sender;
    if (_isNewInput)
    {
        txtDisplay.Text = btn.Text;
        _isNewInput = false;
    }
    else
    {
        txtDisplay.Text += btn.Text;
    }
}

設計重點:_isNewInput 避免運算子按下後、直接輸入數字時殘留舊值。

4. 運算子鍵邏輯

private void OperatorButton_Click(object sender, EventArgs e)
{
    var btn = (Button)sender;
    if (double.TryParse(txtDisplay.Text, out double currentValue))
    {
        if (!_isNewInput && !string.IsNullOrEmpty(_currentOperator))
        {
            // 連續運算:先算出前一個結果
            _firstOperand = Calculate(_firstOperand, currentValue, _currentOperator);
            txtDisplay.Text = _firstOperand.ToString();
        }
        else
        {
            _firstOperand = currentValue;
        }
        _currentOperator = btn.Text;
        _isNewInput = true; // 下一個數字為新輸入
    }
}

5. 等號鍵與計算核心

private void btnEqual_Click(object sender, EventArgs e)
{
    if (double.TryParse(txtDisplay.Text, out double secondOperand) &&
        !string.IsNullOrEmpty(_currentOperator))
    {
        double result = Calculate(_firstOperand, secondOperand, _currentOperator);
        txtDisplay.Text = result.ToString();
        _firstOperand = result; // 支援連續運算
        _currentOperator = "";
        _isNewInput = true;
    }
}

private double Calculate(double a, double b, string op)
{
    return op switch
    {
        "+" => a + b,
        "-" => a - b,
        "*" => a * b,
        "/" => b != 0 ? a / b : double.NaN,
        _ => b
    };
}

6. 清除鍵

private void btnClear_Click(object sender, EventArgs e)
{
    txtDisplay.Text = "0";
    _firstOperand = 0;
    _currentOperator = "";
    _isNewInput = true;
}

7. 進階強化建議

  • 錯誤處理:除零、溢位、非數字輸入攔截
  • 鍵盤支援:覆寫 ProcessCmdKey 接收鍵盤數字與運算子
  • 歷史記錄:ListBox 顯示過往運算式
  • 科學模式:擴充 sin、cos、sqrt、^ 等函數
  • MVVM 重構:將計算邏輯抽離至 ViewModel,方便單元測試

完整程式碼結構

namespace CalculatorApp
{
    public partial class Form1 : Form
    {
        private double _firstOperand;
        private string _currentOperator;
        private bool _isNewInput;

        public Form1() { InitializeComponent(); }

        // 數字鍵 0-9 共用
        private void NumberButton_Click(object sender, EventArgs e) { ... }

        // 運算子 + - * / 共用
        private void OperatorButton_Click(object sender, EventArgs e) { ... }

        private void btnEqual_Click(object sender, EventArgs e) { ... }
        private void btnClear_Click(object sender, EventArgs e) { ... }
        private double Calculate(double a, double b, string op) { ... }
    }
}

小結

本範例展示了 WinForms 事件驅動開發的核心概念:狀態變數管理(_firstOperand、_currentOperator、_isNewInput)、共用事件處理減少重複程式碼、關注點分離(UI 與計算邏輯分離)。掌握此架構,即可輕鬆擴充為功能更豐富的科學計算機。

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