winform写一个计算器
时间: 2023-04-10 13:03:56 浏览: 203
好的,以下是一个简单的 WinForm 计算器的代码示例:
```csharp
using System;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
double num1 = 0;
double num2 = 0;
string operation = "";
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (textBox_Result.Text == "0")
{
textBox_Result.Clear();
}
if (button.Text == ".")
{
if (!textBox_Result.Text.Contains("."))
{
textBox_Result.Text = textBox_Result.Text + button.Text;
}
}
else
{
textBox_Result.Text = textBox_Result.Text + button.Text;
}
}
private void operator_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (num1 != 0)
{
button_Equals.PerformClick();
operation = button.Text;
label_CurrentOperation.Text = num1 + " " + operation;
num1 = double.Parse(textBox_Result.Text);
}
else
{
operation = button.Text;
num1 = double.Parse(textBox_Result.Text);
label_CurrentOperation.Text = num1 + " " + operation;
textBox_Result.Clear();
}
}
private void button_Clear_Click(object sender, EventArgs e)
{
textBox_Result.Text = "0";
num1 = 0;
num2 = 0;
label_CurrentOperation.Text = "";
}
private void button_Equals_Click(object sender, EventArgs e)
{
num2 = double.Parse(textBox_Result.Text);
switch (operation)
{
case "+":
textBox_Result.Text = (num1 + num2).ToString();
break;
case "-":
textBox_Result.Text = (num1 - num2).ToString();
break;
case "*":
textBox_Result.Text = (num1 * num2).ToString();
break;
case "/":
textBox_Result.Text = (num1 / num2).ToString();
break;
default:
break;
}
num1 = double.Parse(textBox_Result.Text);
label_CurrentOperation.Text = "";
}
}
}
```
这个计算器使用了 WinForm 控件,包括文本框、按钮和标签。它支持加、减、乘、除和小数点等操作。
阅读全文