計算機是初學 WinForms 的經典練習題。本文完整呈現從視覺化設計到事件驅動邏輯的實作過程,涵蓋數字鍵輸入、四則運算、清除功能,程式碼結構清晰,適合初學者理解事件處理與狀態管理。
在 Form 上拖放:
TextBox txtDisplay - 顯示輸入與結果,設 ReadOnly = true、靠右對齊Button btn0 ~ Button btn9btnAdd(+)、btnSub(-)、btnMul(*)、btnDiv(/)btnEqual(=)、btnClear(C)建議採用 TableLayoutPanel 排版,固定按鈕大小與間距。
public partial class Form1 : Form
{
private double _firstOperand = 0; // 第一個運算元
private string _currentOperator = ""; // 當前運算子 + - * /
private bool _isNewInput = true; // 標記是否開始新數字輸入
public Form1() { InitializeComponent(); }
}
將所有數字鍵的 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 避免運算子按下後、直接輸入數字時殘留舊值。
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; // 下一個數字為新輸入
}
}
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
};
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Text = "0";
_firstOperand = 0;
_currentOperator = "";
_isNewInput = true;
}
ProcessCmdKey 接收鍵盤數字與運算子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 與計算邏輯分離)。掌握此架構,即可輕鬆擴充為功能更豐富的科學計算機。