帮我用C#语言,写一份计算器的WINDOWS窗口代码
时间: 2024-11-25 13:20:55 浏览: 3
C#编程科学计算器.doc
在C#中创建一个简单的Windows窗体计算器程序,你可以使用Windows Forms库。下面是一个基本的示例,展示了一个简单的加减乘除按钮和两个输入框的计算器:
```csharp
using System;
using System.Windows.Forms;
public partial class CalculatorForm : Form
{
private double _firstNumber = 0;
private double _secondNumber = 0;
public CalculatorForm()
{
InitializeComponent();
}
// 按钮点击事件处理器
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_firstNumber != 0 || _secondNumber != 0)
{
_resultLabel.Text = String.Format("{0} + {1} = ", _firstNumber, _secondNumber);
_firstNumber += Convert.ToDouble(_secondNumber);
_secondNumber = 0;
}
}
private void buttonSubtract_Click(object sender, EventArgs e)
{
if (_firstNumber != 0 || _secondNumber != 0)
{
_resultLabel.Text = String.Format("{0} - {1} = ", _firstNumber, _secondNumber);
_firstNumber -= Convert.ToDouble(_secondNumber);
_secondNumber = 0;
}
}
private void buttonMultiply_Click(object sender, EventArgs e)
{
if (_firstNumber != 0 || _secondNumber != 0)
{
_resultLabel.Text = String.Format("{0} * {1} = ", _firstNumber, _secondNumber);
_firstNumber *= Convert.ToDouble(_secondNumber);
_secondNumber = 0;
}
}
private void buttonDivide_Click(object sender, EventArgs e)
{
if (_firstNumber != 0 && _secondNumber != 0)
{
_resultLabel.Text = String.Format("{0} / {1} = ", _firstNumber, _secondNumber);
_firstNumber /= Convert.ToDouble(_secondNumber);
_secondNumber = 0;
}
}
private void clearButton_Click(object sender, EventArgs e)
{
_firstNumber = 0;
_secondNumber = 0;
_resultLabel.Text = "";
}
// 将文本转换为数字并添加到输入框
private void textBoxInput_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.')
return;
var textBox = (TextBox)sender;
var currentText = textBox.Text;
textBox.Text = currentText + e.KeyChar.ToString();
}
private void textBoxInput_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
_firstNumber = Convert.ToDouble(textBox.Text);
}
private void resultLabel_TextChanged(object sender, EventArgs e)
{
}
}
// 主函数
class Program
{
[STAThread]
static void Main()
{
Application.Run(new CalculatorForm());
}
}
```
这个例子中,我们创建了一个名为CalculatorForm的窗体,包含了四个操作按钮(加、减、乘、除),两个用于输入数字的文本框以及清除按钮。用户可以在文本框内输入数字,然后按相应的运算按钮计算结果。
阅读全文