一.编程思路

1.计算器页面的简单布局;
2.按下对应的数字可以进行显示;
3.第二次输入数时,将第一次输入的数保存并清空文本框;
4.对数值可以进行运算并进行显示;


二.编程核心

1.按下对应的数字进行显示;
2.输入数字进行存储;
3.取出存储数字并进行相应的计算; 4.运算结果的显示;


三.代码实现

1.界面布局:(控件:button,textbox)

C#窗体实现计算机案例_获取焦点

2.窗体加载时代码:

 private void Form1_Load(object sender, EventArgs e)
{
this.CenterToScreen();//设置窗体居中
this.FormBorderStyle = FormBorderStyle.FixedToolWindow;//设置窗体边框样式
textBox1.ReadOnly = true;//设置为仅读
textBox2.Focus();//获取焦点
}

3.对应的数字进行显示:(每个数字都要进行设置,在此只举例一个,下面的依照此格式)

  //7
private void button5_Click(object sender, EventArgs e)
{
//设置按键在textbox显示相应的数字
textBox1.Text += 7;
textBox2.Text += 7;
}

4.按下运算符时,清空文本框:(每个数字都要进行设置,在此只举例一个,下面的依照此格式)

 bool bt = false;//为判断是否按下运算按钮,然后清空textbox1的内容
//7
private void button5_Click(object sender, EventArgs e)
{
if (bt==true)
{
bt = false;
textBox1.Text = "";
}
//设置按键在textbox显示相应的数字
textBox1.Text += 7;
textBox2.Text += 7;
}

5.按下运算符对第一次输入的数字进行保存,并在textbox2显示对应的运算符:

double num1,num2;//存储第一次和第二次textbox1的内容
string type;//记录输入符号
//+
private void button8_Click(object sender, EventArgs e)
{
num1 = double.Parse(textBox1.Text);
bt = true;
type = "+";
textBox2.Text +=type;
}
//-
private void button4_Click(object sender, EventArgs e)
{
num1 = double.Parse(textBox1.Text);
bt = true;
type = "-";
textBox2.Text += type;
}
//×
private void button3_Click(object sender, EventArgs e)
{
num1 = double.Parse(textBox1.Text);
bt = true;
type = "×";
textBox2.Text += type ;
}
//÷
private void button2_Click(object sender, EventArgs e)
{
num1 = double.Parse(textBox1.Text);
bt = true;
type = "÷";
textBox2.Text += type ;
}
//%
private void button18_Click(object sender, EventArgs e)
{
num1 = double.Parse(textBox1.Text);
bt = true;
type = "%";
textBox2.Text += type;
}

6.按下等号时,进行相应的运算并显示结果:

 //=
private void button15_Click(object sender, EventArgs e)
{

num2=double.Parse(textBox1.Text);//存储第二次的输入数
switch (type)
{
case "+":
textBox1.Text = (num1 + num2).ToString();
textBox2.Text += "=" + textBox1.Text;
break;
case "-":
textBox1.Text = (num1 - num2).ToString();
textBox2.Text += "=" + textBox1.Text;
break;
case "×":
textBox1.Text = (num1 * num2).ToString();
textBox2.Text += "=" + textBox1.Text;
break;
case "÷":
if (num2 != 0)//被除数不能为零,进行判断
{
textBox1.Text = (num1 / num2).ToString();
textBox2.Text += "=" + textBox1.Text;
}
else//如果为零进行报错,并清空输入的数值
MessageBox.Show("输入错误!");
textBox1.Text="";
textBox2.Text="";
break;
case "%":
textBox1.Text = (num1 % num2).ToString();
textBox2.Text += "=" + textBox1.Text;
break;
default:
break;
}
}

7.点击ESC时清空输入的内容:

 //ESC
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
}



四.运行结果:

C#窗体实现计算机案例_经验分享_02

C#窗体实现计算机案例_运算符_03

C#窗体实现计算机案例_文本框_04