单击相等按钮或输入(键盘)后,我希望我的计算器取一个新数字,基本上好像TextBox中没有任何内容,即使答案仍然显示。
目前,所有号码都会保留,新号码会添加到最后。在计算之后,如果我点击一个数字按钮或小键盘(键盘),我希望它清除TextBox并添加新的数字。
例如,2 + 2 = 4,当我输入一个像5这样的新数字时,TextBox不会清除在单击等号或输入(键盘)后已经在TextBox中的数字(4),TextBox认为我想要它说45但我希望只要在点击等号或输入(键盘)后输入新号码就可以清除号码。
如果您不介意,您是否也会举例说明使用我的代码解决此问题您将采取的措施。
public partial class Form1 : Form
{
Double value = 0;
String operation = "";
bool operation_pressed = false;
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
if ((textBoxResult.Text == "0")||(operation_pressed))
textBoxResult.Clear();
operation_pressed = false;
Button b = (Button)sender;
if (b.Text == ".")
{
if (!textBoxResult.Text.Contains("."))
textBoxResult.Text = textBoxResult.Text + b.Text;
}
else
textBoxResult.Text = textBoxResult.Text + b.Text;
}
private void operator_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (value != 0)
{
buttonEqual.PerformClick();
operation_pressed = true;
operation = b.Text;
labelEquation.Text = value + " " + operation;
}
else
{
operation = b.Text;
value = Double.Parse(textBoxResult.Text);
operation_pressed = true;
labelEquation.Text = value + " " + operation;
}
}
private void buttonEqual_Click(object sender, EventArgs e)
{
labelEquation.Text = "";
switch(operation)
{
case "+":
textBoxResult.Text = (value + Double.Parse(textBoxResult.Text)).ToString();
break;
case "-":
textBoxResult.Text = (value - Double.Parse(textBoxResult.Text)).ToString();
break;
case "*":
textBoxResult.Text = (value * Double.Parse(textBoxResult.Text)).ToString();
break;
case "/":
textBoxResult.Text = (value / Double.Parse(textBoxResult.Text)).ToString();
break;
default:
break;
}
value = Doudble.Parse(textBoxResult.Text);
operation = "";
}
private void buttonClearEntry_Click(object sender, EventArgs e)
{
textBoxResult.Text = "0";
}
private void buttonClear_Click(object sender, EventArgs e)
{
textBoxResult.Text = "0";
value = 0;
labelEquation.Text = "";
}
private void keyboard_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.KeyChar.ToString())
{
case "0":
buttonZero.PerformClick();
break;
case "1":
buttonOne.PerformClick();
break;
case "2":
buttonTwo.PerformClick();
break;
case "3":
buttonThree.PerformClick();
break;
case "4":
buttonFour.PerformClick();
break;
case "5":
buttonFive.PerformClick();
break;
case "7":
buttonSeven.PerformClick();
break;
case "8":
buttonEight.PerformClick();
break;
case "9":
buttonNine.PerformClick();
break;
case ".":
buttonPeriod.PerformClick();
break;
case "+":
buttonAddition.PerformClick();
break;
case "-":
buttonMinus.PerformClick();
break;
case "*":
buttonMultiply.PerformClick();
break;
case "/":
buttonDivide.PerformClick();
break;
case "=":
buttonEqual.PerformClick();
break;
default:
break;
}
}
}