winform实现计算器-保姆级教程
哈喽大家好,今天想和大家分享一下用winform实现一个简单的计算器。这个案例特别适合刚学winform的小伙伴,锻炼价值特别高。能把前面学的winfrom知识用一遍,而且逻辑也不是特别复杂,对新手比较友好。
目录
一.效果展示
二.创建项目
三.编辑界面
四.编写逻辑代码
4.1处理控件的点击事件
什么是事件?
生成控件初始化代码
在屏幕上展示用户点击的按钮
4.2处理运算逻辑
判断是什么符号
实现四则运算
五.全部代码
1.界面设计代码(Form1.Designer.cs)
2.逻辑代码(Form1.cs)
3.程序入口(Program.cs)
一.效果展示
支持简单的四则运算取余操作


二.创建项目
万丈高楼平地起,我们先从创建项目开始吧。
打开vs2022 -> 点击创建项目 -> 选择winfrom -> 下一步

填写项目名称,选择项目位置

三.编辑界面
在创建好项目之后就可以编辑界面了,主要利用“button”(按钮) 控件
从“工具箱”拖一个“button“控件到窗体上,把该控件的属性“Text”改成1,字体和颜色改成合适的(这个可以随意发挥自己的创意)

然后用上面同样的方法重复操作,直到把界面做成这样子,注意控件上显示上面文字取决于该控件的属性“Text”

界面的样式就做的差不多了,是不是有一点小小的成就感?当然我们还要编写后台逻辑代码
在写逻辑代码之前,我们还要给控件起一个名字。该操作的主要目的是为了让我们自己分清楚,哪个控件对应哪段代码,更加直观。小编之前踩过坑
0-9分别对应button0-button9,加减乘除取余对应add.sub.mul.div.Surplus,点号是spot,等于号是Equal,清零是Clear,结果展示区是Expression

四.编写逻辑代码
4.1处理控件的点击事件
什么是事件?
可以理解成一个行为,通过用户的某种操作,程序会执行预先写好的代码来响应它。
比如说我点击一个按钮"1",程序能在一个区域显示"1"

计算器程序就正需要一个这样的点击事件,来反馈给用户他点击了什么
接下来我们就来一步一步实现该效果吧
生成控件初始化代码
双击控件就会在From.cs文件中生成对应的代码,让每一个控件都生成一段代码

在屏幕上展示用户点击的按钮
想实现这个效果很简单,只要在点击该控件的时候,把 Expression.Text 改成对应的值即可
例如这样

但是这样做会存在很多冗余的代码,我们可以定义一个全局变量来记录每次点击的值,和一个公共方法来拼接每次点击的值。
public static string GlobalExpresssion = ""; //用来记录每次用户点击按钮的数字
public void AppendNumber(string num) //每次用户点击按钮时调用该控件就可以展示了
{GlobalExpresssion += num;Expression.Text = GlobalExpresssion;
}
清除按钮只需要把Expression.Text改成空值即可
按键部分代码
#region 按键private void add_Click(object sender, EventArgs e){AppendNumber("+");}private void sub_Click(object sender, EventArgs e){AppendNumber("-");}private void mul_Click(object sender, EventArgs e){AppendNumber("*");}private void div_Click(object sender, EventArgs e){AppendNumber("/");}private void Equal_Click(object sender, EventArgs e){}private void spot_Click(object sender, EventArgs e){AppendNumber(".");}private void Surplus_Click(object sender, EventArgs e){AppendNumber("%");}private void Clear_Click(object sender, EventArgs e) //点清空Expression.Text改成空值{GlobalExpresssion = "";Expression.Text = "";}private void button1_Click(object sender, EventArgs e){AppendNumber("1");}private void button2_Click(object sender, EventArgs e){AppendNumber("2");}private void button3_Click(object sender, EventArgs e){AppendNumber("3");}private void button4_Click(object sender, EventArgs e){AppendNumber("4");}private void button5_Click(object sender, EventArgs e){AppendNumber("5");}private void button6_Click(object sender, EventArgs e){AppendNumber("6");}private void button7_Click(object sender, EventArgs e){AppendNumber("7");}private void button8_Click(object sender, EventArgs e){AppendNumber("8");}private void button9_Click(object sender, EventArgs e){AppendNumber("9");}private void button0_Click(object sender, EventArgs e){AppendNumber("0");}#endregion
}
这样就可以展示用户点击的按钮了

4.2处理运算逻辑
在理想情况下输入两个数希望当点击等于号的时候就计算出结果,所以需要定义一个方法来计算。该方法能够实现基本的运算
public string Operation(string num) //当点击等于号的时候就调用该方法{//运算逻辑return GlobalExpresssion; //}
判断是什么符号
在Operation方法中需要判断是什么符号并处理对应的运算逻辑,我们之前是把数字和运算符号拼接在全局变量里面,例如10+10这样,可以用Contains来判断该字符串里面有没有对应的运算符号
Contains使用方法
会返回一个bool类型的值,如果存在返回true,不存在则返回false
public string Operation(string num) //当点击等于号的时候就调用该方法{if(GlobalExpresssion.Contains("+")){}else if(GlobalExpresssion.Contains("-")){}else if (GlobalExpresssion.Contains("*")){}else if (GlobalExpresssion.Contains("/")){}else if (GlobalExpresssion.Contains("%")){}return GlobalExpresssion; //}
这样就可以判断用户想要进行什么样的运算了
实现四则运算
由于我们之前是把数字和运算符号拼接在全局变量里面,所以需要把字符串以运算符号为界限切割开便于计算。
可以使用Split,来进行切割
Split使用方法
string[] result = str.Split(分隔符, 选项);string text = "apple,banana,orange";
string[] fruits = text.Split(','); //以逗号为界限进行切割
// 结果: ["apple", "banana", "orange"]
注意事项:字符串不能直接运算,还要做转换
具体代码
public string Operation(string num) //当点击等于号的时候就调用该方法{if(GlobalExpresssion.Contains("+")){string[] temps = GlobalExpresssion.Split('+');GlobalExpresssion = (Convert.ToDecimal(temps[0]) + Convert.ToDecimal(temps[1])).ToString();}else if(GlobalExpresssion.Contains("-")){string[] temps = GlobalExpresssion.Split('-');GlobalExpresssion = (Convert.ToDecimal(temps[0]) - Convert.ToDecimal(temps[1])).ToString();}else if (GlobalExpresssion.Contains("*")){string[] temps = GlobalExpresssion.Split('*');GlobalExpresssion = (Convert.ToDecimal(temps[0]) * Convert.ToDecimal(temps[1])).ToString();}else if (GlobalExpresssion.Contains("/")){string[] temps = GlobalExpresssion.Split('/');GlobalExpresssion = (Convert.ToDecimal(temps[0]) / Convert.ToDecimal(temps[1])).ToString();}else if (GlobalExpresssion.Contains("%")){string[] temps = GlobalExpresssion.Split('%');GlobalExpresssion = (Convert.ToDecimal(temps[0]) % Convert.ToDecimal(temps[1])).ToString();}return GlobalExpresssion; //}
这样一个简单的计算器就实现出来了,但是还有一些值得优化的地方
五.全部代码
1.界面设计代码(Form1.Designer.cs)
namespace calculator
{partial class Form1{/// <summary>/// 必需的设计器变量。/// </summary>private System.ComponentModel.IContainer components = null;/// <summary>/// 清理所有正在使用的资源。/// </summary>/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}#region Windows 窗体设计器生成的代码/// <summary>/// 设计器支持所需的方法 - 不要修改/// 使用代码编辑器修改此方法的内容。/// </summary>private void InitializeComponent(){this.Expression = new System.Windows.Forms.Button();this.Surplus = new System.Windows.Forms.Button();this.Clear = new System.Windows.Forms.Button();this.div = new System.Windows.Forms.Button();this.Equal = new System.Windows.Forms.Button();this.spot = new System.Windows.Forms.Button();this.mul = new System.Windows.Forms.Button();this.sub = new System.Windows.Forms.Button();this.add = new System.Windows.Forms.Button();this.button0 = new System.Windows.Forms.Button();this.button9 = new System.Windows.Forms.Button();this.button8 = new System.Windows.Forms.Button();this.button7 = new System.Windows.Forms.Button();this.button6 = new System.Windows.Forms.Button();this.button5 = new System.Windows.Forms.Button();this.button4 = new System.Windows.Forms.Button();this.button3 = new System.Windows.Forms.Button();this.button2 = new System.Windows.Forms.Button();this.button1 = new System.Windows.Forms.Button();this.SuspendLayout();// // Expression// this.Expression.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.Expression.Location = new System.Drawing.Point(12, 35);this.Expression.Name = "Expression";this.Expression.Size = new System.Drawing.Size(392, 67);this.Expression.TabIndex = 37;this.Expression.TextAlign = System.Drawing.ContentAlignment.TopRight;this.Expression.UseVisualStyleBackColor = true;// // Surplus// this.Surplus.FlatStyle = System.Windows.Forms.FlatStyle.System;this.Surplus.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.Surplus.Location = new System.Drawing.Point(227, 125);this.Surplus.Name = "Surplus";this.Surplus.Size = new System.Drawing.Size(177, 67);this.Surplus.TabIndex = 36;this.Surplus.Text = "取余";this.Surplus.UseVisualStyleBackColor = true;this.Surplus.Click += new System.EventHandler(this.Surplus_Click);// // Clear// this.Clear.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.Clear.Location = new System.Drawing.Point(12, 125);this.Clear.Name = "Clear";this.Clear.Size = new System.Drawing.Size(177, 67);this.Clear.TabIndex = 35;this.Clear.Text = "清零";this.Clear.UseVisualStyleBackColor = true;this.Clear.Click += new System.EventHandler(this.Clear_Click);// // div// this.div.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.div.Location = new System.Drawing.Point(323, 570);this.div.Name = "div";this.div.Size = new System.Drawing.Size(72, 67);this.div.TabIndex = 34;this.div.Text = "/";this.div.UseVisualStyleBackColor = true;this.div.Click += new System.EventHandler(this.div_Click);// // Equal// this.Equal.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.Equal.Location = new System.Drawing.Point(227, 570);this.Equal.Name = "Equal";this.Equal.Size = new System.Drawing.Size(72, 67);this.Equal.TabIndex = 33;this.Equal.Text = "=";this.Equal.UseVisualStyleBackColor = true;this.Equal.Click += new System.EventHandler(this.Equal_Click);// // spot// this.spot.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.spot.Location = new System.Drawing.Point(117, 570);this.spot.Name = "spot";this.spot.Size = new System.Drawing.Size(72, 67);this.spot.TabIndex = 32;this.spot.Text = ".";this.spot.UseVisualStyleBackColor = true;this.spot.Click += new System.EventHandler(this.spot_Click);// // mul// this.mul.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.mul.Location = new System.Drawing.Point(323, 464);this.mul.Name = "mul";this.mul.Size = new System.Drawing.Size(72, 67);this.mul.TabIndex = 31;this.mul.Text = "*";this.mul.UseVisualStyleBackColor = true;this.mul.Click += new System.EventHandler(this.mul_Click);// // sub// this.sub.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.sub.Location = new System.Drawing.Point(323, 354);this.sub.Name = "sub";this.sub.Size = new System.Drawing.Size(72, 67);this.sub.TabIndex = 30;this.sub.Text = "-";this.sub.UseVisualStyleBackColor = true;this.sub.Click += new System.EventHandler(this.sub_Click);// // add// this.add.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.add.Location = new System.Drawing.Point(323, 239);this.add.Name = "add";this.add.Size = new System.Drawing.Size(72, 67);this.add.TabIndex = 29;this.add.Text = "+";this.add.UseVisualStyleBackColor = true;this.add.Click += new System.EventHandler(this.add_Click);// // button0// this.button0.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button0.Location = new System.Drawing.Point(12, 570);this.button0.Name = "button0";this.button0.Size = new System.Drawing.Size(72, 67);this.button0.TabIndex = 28;this.button0.Text = "0";this.button0.UseVisualStyleBackColor = true;this.button0.Click += new System.EventHandler(this.button0_Click);// // button9// this.button9.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button9.Location = new System.Drawing.Point(227, 464);this.button9.Name = "button9";this.button9.Size = new System.Drawing.Size(72, 67);this.button9.TabIndex = 27;this.button9.Text = "9";this.button9.UseVisualStyleBackColor = true;this.button9.Click += new System.EventHandler(this.button9_Click);// // button8// this.button8.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button8.Location = new System.Drawing.Point(117, 464);this.button8.Name = "button8";this.button8.Size = new System.Drawing.Size(72, 67);this.button8.TabIndex = 26;this.button8.Text = "8";this.button8.UseVisualStyleBackColor = true;this.button8.Click += new System.EventHandler(this.button8_Click);// // button7// this.button7.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button7.Location = new System.Drawing.Point(12, 464);this.button7.Name = "button7";this.button7.Size = new System.Drawing.Size(72, 67);this.button7.TabIndex = 25;this.button7.Text = "7";this.button7.UseVisualStyleBackColor = true;this.button7.Click += new System.EventHandler(this.button7_Click);// // button6// this.button6.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button6.Location = new System.Drawing.Point(227, 354);this.button6.Name = "button6";this.button6.Size = new System.Drawing.Size(72, 67);this.button6.TabIndex = 24;this.button6.Text = "6";this.button6.UseVisualStyleBackColor = true;this.button6.Click += new System.EventHandler(this.button6_Click);// // button5// this.button5.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button5.Location = new System.Drawing.Point(117, 354);this.button5.Name = "button5";this.button5.Size = new System.Drawing.Size(72, 67);this.button5.TabIndex = 23;this.button5.Text = "5";this.button5.UseVisualStyleBackColor = true;this.button5.Click += new System.EventHandler(this.button5_Click);// // button4// this.button4.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button4.Location = new System.Drawing.Point(12, 354);this.button4.Name = "button4";this.button4.Size = new System.Drawing.Size(72, 67);this.button4.TabIndex = 22;this.button4.Text = "4";this.button4.UseVisualStyleBackColor = true;this.button4.Click += new System.EventHandler(this.button4_Click);// // button3// this.button3.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button3.Location = new System.Drawing.Point(227, 239);this.button3.Name = "button3";this.button3.Size = new System.Drawing.Size(72, 67);this.button3.TabIndex = 21;this.button3.Text = "3";this.button3.UseVisualStyleBackColor = true;this.button3.Click += new System.EventHandler(this.button3_Click);// // button2// this.button2.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button2.Location = new System.Drawing.Point(117, 239);this.button2.Name = "button2";this.button2.Size = new System.Drawing.Size(72, 67);this.button2.TabIndex = 20;this.button2.Text = "2";this.button2.UseVisualStyleBackColor = true;this.button2.Click += new System.EventHandler(this.button2_Click);// // button1// this.button1.Font = new System.Drawing.Font("宋体", 26F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.button1.Location = new System.Drawing.Point(12, 239);this.button1.Name = "button1";this.button1.Size = new System.Drawing.Size(72, 67);this.button1.TabIndex = 19;this.button1.Text = "1";this.button1.UseVisualStyleBackColor = true;this.button1.Click += new System.EventHandler(this.button1_Click);// // Form1// this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.ClientSize = new System.Drawing.Size(422, 650);this.Controls.Add(this.Expression);this.Controls.Add(this.Surplus);this.Controls.Add(this.Clear);this.Controls.Add(this.div);this.Controls.Add(this.Equal);this.Controls.Add(this.spot);this.Controls.Add(this.mul);this.Controls.Add(this.sub);this.Controls.Add(this.add);this.Controls.Add(this.button0);this.Controls.Add(this.button9);this.Controls.Add(this.button8);this.Controls.Add(this.button7);this.Controls.Add(this.button6);this.Controls.Add(this.button5);this.Controls.Add(this.button4);this.Controls.Add(this.button3);this.Controls.Add(this.button2);this.Controls.Add(this.button1);this.Name = "Form1";this.Text = "Form1";this.ResumeLayout(false);}#endregionprivate System.Windows.Forms.Button Expression;private System.Windows.Forms.Button Surplus;private System.Windows.Forms.Button Clear;private System.Windows.Forms.Button div;private System.Windows.Forms.Button Equal;private System.Windows.Forms.Button spot;private System.Windows.Forms.Button mul;private System.Windows.Forms.Button sub;private System.Windows.Forms.Button add;private System.Windows.Forms.Button button0;private System.Windows.Forms.Button button9;private System.Windows.Forms.Button button8;private System.Windows.Forms.Button button7;private System.Windows.Forms.Button button6;private System.Windows.Forms.Button button5;private System.Windows.Forms.Button button4;private System.Windows.Forms.Button button3;private System.Windows.Forms.Button button2;private System.Windows.Forms.Button button1;}
}
2.逻辑代码(Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace calculator
{public partial class Form1 : Form{public Form1(){InitializeComponent();}public static string GlobalExpresssion = "";public void AppendNumber(string num){GlobalExpresssion += num;Expression.Text = GlobalExpresssion;}public string Operation(string num) //当点击等于号的时候就调用该方法{if(GlobalExpresssion.Contains("+")){string[] temps = GlobalExpresssion.Split('+');GlobalExpresssion = (Convert.ToDecimal(temps[0]) + Convert.ToDecimal(temps[1])).ToString();}else if(GlobalExpresssion.Contains("-")){string[] temps = GlobalExpresssion.Split('-');GlobalExpresssion = (Convert.ToDecimal(temps[0]) - Convert.ToDecimal(temps[1])).ToString();}else if (GlobalExpresssion.Contains("*")){string[] temps = GlobalExpresssion.Split('*');GlobalExpresssion = (Convert.ToDecimal(temps[0]) * Convert.ToDecimal(temps[1])).ToString();}else if (GlobalExpresssion.Contains("/")){string[] temps = GlobalExpresssion.Split('/');GlobalExpresssion = (Convert.ToDecimal(temps[0]) / Convert.ToDecimal(temps[1])).ToString();}else if (GlobalExpresssion.Contains("%")){string[] temps = GlobalExpresssion.Split('%');GlobalExpresssion = (Convert.ToDecimal(temps[0]) % Convert.ToDecimal(temps[1])).ToString();}return GlobalExpresssion; //}#region 按键private void add_Click(object sender, EventArgs e){AppendNumber("+");}private void sub_Click(object sender, EventArgs e){AppendNumber("-");}private void mul_Click(object sender, EventArgs e){AppendNumber("*");}private void div_Click(object sender, EventArgs e){AppendNumber("/");}private void Equal_Click(object sender, EventArgs e){Expression.Text = Operation("=");}private void spot_Click(object sender, EventArgs e){AppendNumber(".");}private void Surplus_Click(object sender, EventArgs e){AppendNumber("%");}private void Clear_Click(object sender, EventArgs e){GlobalExpresssion = "";Expression.Text = "";}private void button1_Click(object sender, EventArgs e){AppendNumber("1");}private void button2_Click(object sender, EventArgs e){AppendNumber("2");}private void button3_Click(object sender, EventArgs e){AppendNumber("3");}private void button4_Click(object sender, EventArgs e){AppendNumber("4");}private void button5_Click(object sender, EventArgs e){AppendNumber("5");}private void button6_Click(object sender, EventArgs e){AppendNumber("6");}private void button7_Click(object sender, EventArgs e){AppendNumber("7");}private void button8_Click(object sender, EventArgs e){AppendNumber("8");}private void button9_Click(object sender, EventArgs e){AppendNumber("9");}private void button0_Click(object sender, EventArgs e){AppendNumber("0");}#endregion}
}
3.程序入口(Program.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;namespace calculator
{internal static class Program{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new Form1());}}
}
