C#入門計算器
阿新 • • 發佈:2018-12-12
這個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 } }