[英]How to correctly use ProcessCmdKey in a calculator windows form application?
我正在尝试在C#Windows窗体应用程序中构建普通计算器。 我希望当我按下任意数字键时,数字将显示在文本框中,就像在任何标准计算器中一样。
因此,通过研究,我可以通过重写ProcessCmdKey
并将Form的KeyPreview
属性更改为true
来完成此操作。
但是问题是:当我完全使用数字键盘时,计算器可以正常工作。 但是当我组合鼠标单击任意数字按钮,然后尝试再次使用数字键盘时,数字不会显示在TextBox中。
我有一个通用的数字按钮点击方法(它将触发0-9所有按钮点击)
private void number_button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
textBox1.Text = textBox1.Text + "" + button.Text;
}
加法(类似于减法,除法,乘法的明智方法)
private void buttonPlusClk_Click(object sender, EventArgs e)
{
sign = "+";
operandOne = double.Parse(textBox1.Text);
textBox1.Text = "";
}
申请表格
this.KeyPreview = true;
重写的ProcessCmdKey
方法
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.NumPad0 |
Keys.NumPad1 |
Keys.NumPad2 |
Keys.NumPad3 |
Keys.NumPad4 |
Keys.NumPad5 |
Keys.NumPad6 |
Keys.NumPad7 |
Keys.NumPad8 |
Keys.NumPad9))
{
// also not sure about the KeyEventArgs(keyData)... is it ok?
number_button_Click(keyData, new KeyEventArgs(keyData));
return true;
}
else if(keyData == (Keys.Add))
{
buttonPlusClk_Click(keyData, new KeyEventArgs(keyData));
return true;
}
// ... and the if conditions for other operators
return base.ProcessCmdKey(ref msg, keyData);
}
问我是否要查看其他代码。
为了将来参考, 请从GitHub获取SSCCE并重新创建问题,请执行此操作
2
+
1
(您不会在文本框中看到1) 在您的密钥处理功能中尝试此操作。 不用作标志的XOR'ing数字不正确。
同样,从该函数调用事件处理程序也会导致错误,因为第一个arg不是按钮。
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
int intKey = (int)keyData;
if (intKey >= 96 && intKey <= 105) // 96 = 0, 97 = 1, ..., 105 = 9
{
textBox1.Text = textBox1.Text + (intKey - 96).ToString();
return true;
}
// ... and the if conditions for other operators
return base.ProcessCmdKey(ref msg, keyData);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.