【发布时间】:2017-10-06 19:07:38
【问题描述】:
我目前正在尝试编写一个简单的 Winforms 计算器,并且正在努力将 NumPad 键分配给表单按钮。到目前为止,我分配的每个按钮都可以正常工作,但 Enter 按钮除外。无论输入的表达式是什么,当按下物理回车键时,它都会在答案here 的末尾添加一个单独的“1”。只需按下表单按钮,它就可以正常工作。 有人知道这是为什么,或者可以帮助我吗? 我也意识到我的一些代码是不需要的,所以放过我吧,我只是个学生!
以下是关键检测代码及其引入的相关方法:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
enterButton.PerformClick();
}
if (keyData == Keys.NumPad0)
{
button10.PerformClick();
}
if (keyData == Keys.NumPad1)
{
button1.PerformClick();
}
if (keyData == Keys.NumPad2)
{
button2.PerformClick();
}
if (keyData == Keys.NumPad3)
{
button3.PerformClick();
}
if (keyData == Keys.NumPad4)
{
button4.PerformClick();
}
if (keyData == Keys.NumPad5)
{
button5.PerformClick();
}
if (keyData == Keys.NumPad6)
{
button6.PerformClick();
}
if (keyData == Keys.NumPad7)
{
button7.PerformClick();
}
if (keyData == Keys.NumPad8)
{
button8.PerformClick();
}
if (keyData == Keys.NumPad9)
{
button9.PerformClick();
}
if (keyData == Keys.Add)
{
addButton.PerformClick();
}
if (keyData == Keys.Subtract)
{
minusButton.PerformClick();
}
if (keyData == Keys.Multiply)
{
timesButton.PerformClick();
}
if (keyData == Keys.Divide)
{
divideButton.PerformClick();
}
}
private void enterButton_Click(object sender, EventArgs e)
{
operIsDone = true; //triggers final calculation
MainCalc();
}
private void MainCalc()
{
do
{
if (operation == '+')
{
operand = stringToInt(inputString);
inputString = cleared;
ansCache += operand;
operand = 0;
break;
}
if (operation == '-')
{
if (minusButton.Tag.Equals("1"))
{
operand = stringToInt(inputString);
inputString = cleared;
ansCache += operand;
minusButton.Tag = "2";
break;
}
else if (minusButton.Tag.Equals("2"))
{
operand = stringToInt(inputString);
inputString = cleared;
ansCache -= operand;
break;
}
}
if(operation == '*')
{
if (timesButton.Tag.Equals("1"))
{
operand = stringToInt(inputString);
inputString = cleared;
ansCache += operand;
timesButton.Tag = "2";
break;
}
else if (timesButton.Tag.Equals("2"))
{
operand = stringToInt(inputString);
inputString = cleared;
ansCache *= operand;
break;
}
}
if(operation == '/')
{
if (divideButton.Tag.Equals("1"))
{
operand = stringToInt(inputString);
inputString = cleared;
ansCache += operand;
divideButton.Tag = "2";
break;
}
else if (divideButton.Tag.Equals("2"))
{
operand = stringToInt(inputString);
inputString = cleared;
if (operand != 0)
{
ansCache /= operand;
}
else
{
statusLabel.Text = "Cannot Divide By Zero!";
}
break;
}
}
else if(operIsDone) { break; }
}
while (calc);
if (operIsDone)
{
statusLabel.Text = Convert.ToString(ansCache) + "";
statusText = statusLabel.Text;
}
【问题讨论】:
-
你能上传整个 ProcessCmdKey 我感觉里面发生了什么事。或指向您的 git 存储库的链接,此代码所在的位置
-
我有根据的猜测是 1 的按钮被设置为表单的 AcceptButton,这可能导致事件被触发两次。
-
我会尝试将 System.Diagnostics.Debug.WriteLine 添加到 main calc 的开头,我会怀疑 1 键被设置为 else 语句或导致它调用的那种性质的东西maincalc 也是如此
-
ProcessCmdKey 似乎仍然不完整。
-
抱歉,-1 来自处理网络应用程序,其中 -1 表示控件已脱离表单的 Tab 键顺序。所以,看看我的回答。基本上,您的 Enter 键被处理为 cmd 键和单击任何具有焦点的按钮。这是回车键的典型行为。
标签: c# winforms calculator