设计一个窗体ComForm,它有一个文本框textBox1,一个标签lable1和16个按钮命令(button5的标题为“+”,button8的标题为“-”,button12的标题为“*”,button16的标题为“/”,button15的标题为“=”,button14的标题为“.”,其他的按行一个一个挨着来(因为我昂搞得时候标签弄得有点乱)
分析:本窗体的16个按钮分为了两组,一个是包括小数点在内的数字组,另一个则是运算符组。数字组所有单击操作都是类似的,他们共享一个事件过程buttoned_Click。同样的,运算符组共享的是buttonop_Click。
代码实现:
namespace WindowsFormsApplication2
{
public partial class ComForm : Form
{
private string s; //保存用户所按的运算符
private double x, y; //保存用户所输入的运算数
private Button btn; //运算符按钮对象
public ComForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = " ";
label1.Text = " ";
}
//单击数字命令按钮的事件过程
private void buttonod_Click(object sender, EventArgs e)
{
btn = (Button)sender;
textBox1.Text = textBox1.Text + btn.Text;
}
//单击运算符命令按钮的事件过程
private void buttonop_Click(object sender, EventArgs e)
{
btn = (Button)sender; //将sender强制转换为Button类型
if (btn.Name != "button15") //用户不是单击“=”命令按钮
{
x = Convert.ToDouble(textBox1.Text);
textBox1.Text =" ";
s = btn.Name; //保存用户按键
label1.Text = x.ToString();
}
else //用户单击“=”按钮
{
if (label1.Text == " ")
MessageBox.Show("输入不正确", "信息提示", MessageBoxButtons.OK);
else
{
y = Convert.ToDouble(textBox1.Text);
switch (s)
{
case "button5": //用户刚在前面单击“+”命令按钮
textBox1.Text = (x + y).ToString();
break;
case "button8": //用户刚在前面单击“-”命令按钮
textBox1.Text = (x - y).ToString();
break;
case "button12": //用户刚在前面单击“*”命令按钮
textBox1.Text = (x * y).ToString();
break;
case "button16": //用户刚在前面单击“/”命令按钮
if (y == 0)
MessageBox.Show("除零错误", "信息提示", MessageBoxButtons.OK);
else
textBox1.Text = (x / y).ToString();
break;
}
label1.Text = textBox1.Text;
}
}
}
}
}
运行结果: