这个demo写了个大概,还可以看看吧,就是计算器里面的四则运算,下面是代码。高手勿喷。
其余的功能没有写全。代码也没加备注。还有调用接口的地方是因为我把自己的小demo全做成了插件的形式。
namespace Plugin.CalcDemo
{
public partial class CalcFrm : Form,CRM.IPlugin.IVote
{
public CalcFrm()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
this.Text = "计算器";
this.textBox1.Text = "";
this.textBox2.Text = "";
}
public double inputA;
public bool isNew=true;
public string Operator;
public double inputB;
public void BtnNumClick(object sender, EventArgs e)
{
//第一次输入
if (isNew)
{
textBox2.Text += Convert.ToDouble((sender as Button).Text);
}
//这里是在执行 = 号运算完成之后,text里面的数字需要更新
else
{
textBox2.Text = "";
textBox2.Text += Convert.ToDouble((sender as Button).Text);
isNew = true;
}
}
public void BtnOpera(object sender, EventArgs e)
{
//text2为空,text1不为空,这个时候 可以刷新运算符,(得到最后一次按下的运算符)
if (string.IsNullOrEmpty(textBox2.Text)&textBox1.Text!="" )
{
Operator = (sender as Button).Tag.ToString();
textBox1.Text = inputA + (sender as Button).Tag.ToString();
}
//这个判断就是 下面输入的text2不是空的时候(输入了数字),这时候,当你按下 运算符
//这时候将你第一次输入的数字保存到 inputA 然后记录下运算符,(此时情况 上面的有数字 和运算符)
//下面的清空了(如果更改运算符,就会执行第一次的判断)
else if (string.IsNullOrEmpty(textBox1.Text) & textBox2.Text != "")
{
inputA = Convert.ToDouble(textBox2.Text);
textBox2.Text = "";
Operator = (sender as Button).Tag.ToString();
textBox1.Text = inputA + (sender as Button).Tag.ToString();
}
//这个判断就是,此时的情景上面下面都有数据,这时候按下运算符执行的就是 用运算符触发计算的事件,
//这个地方执行的就是触发了 = 的计算方式。
else if (textBox2.Text != null& textBox1.Text != null)
{
BtnCalc(this, e);
Operator = (sender as Button).Tag.ToString();
inputA = Convert.ToDouble(textBox2.Text);
textBox2.Text = "";
textBox1.Text = inputA + Operator;
}
}
public void BtnCalc(object sender, EventArgs e)
{
if (textBox2.Text=="")
{
return;
}
if (isNew)
{
inputB = Convert.ToDouble(textBox2.Text);
switch (Operator)
{
case "+":
inputA = inputA + Convert.ToDouble(textBox2.Text);
break;
case "-":
inputA = inputA - Convert.ToDouble(textBox2.Text);
break;
case "*":
inputA = inputA * Convert.ToDouble(textBox2.Text);
break;
default:
inputA = inputA / Convert.ToDouble(textBox2.Text);
break;
}
textBox1.Text = "";
textBox2.Text = inputA.ToString();
}
else
{
switch (Operator)
{
case "+":
inputA = inputA + inputB;
break;
case "-":
inputA = inputA - inputB;
break;
case "*":
inputA = inputA * inputB;
break;
default:
inputA = inputA / inputB;
break;
}
textBox1.Text = "";
textBox2.Text = inputA.ToString();
}
isNew = false;
}
#region 调用接口部分
public void SetUp()
{
FormCollection formCollection = Application.OpenForms;
if (formCollection[this.Name] != null)
{
(formCollection[this.Name] as Form).WindowState = FormWindowState.Normal;
(formCollection[this.Name] as Form).Focus();
// (formCollection[this.Name] as Form).IsMdiContainer = false;
this.Dispose();
}
else
{
this.Show();
}
}
public string GetPluginName()
{
return "计算器";
}
#endregion
}
}