将 kepypress 事件添加到基本计算器表单



我在Visual Studio中制作了一个基本的计算器表单,它使用鼠标单击事件功能齐全。我正在尝试添加键盘按下事件,以便您可以使用键盘或鼠标,但无法弄清楚。

我为按键事件添加了一些代码,但它只有在我先鼠标单击按钮时才有效,然后键盘事件将起作用,如果我鼠标选择另一个数字,它将停止工作。

//Code that handles click events
private void number_Click(object sender, EventArgs e)
{
if((txtResult.Text == "0")||(operation))
{
txtResult.Clear();
}           
//Cast button to the object sender
operation = false;
Button button = (Button)sender;
//If the button pressed is a "." then check if the txtResult already contains
//a ".", if it does contain a "." then do nothing
if (button.Text == ".")
{
if (!txtResult.Text.Contains("."))
{
txtResult.Text = txtResult.Text + button.Text;
}
}else
txtResult.Text = txtResult.Text + button.Text;
}

//Keyboard press event code
private void num1_key(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1')
{
//If keyboard '1' pressed perform number_click()
btn1.PerformClick();
e.Handled = true;
}
}

我错过了什么明显的东西还是我走错了路?

更新的答案

由于您仍然遇到问题,因此您要做的是删除以前的代码并使用以下代码。

//Have your form's KeyPress event like this, replace textBox1 with the name of your textbox
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.KeyChar)
{
case '0':
textBox1.Text += "0";
break;
case '1':
textBox1.Text += "1";
break;
case '2':
textBox1.Text += "2";
break;
case '3':
textBox1.Text += "3";
break;
case '4':
textBox1.Text += "4";
break;
case '5':
textBox1.Text += "5";
break;
case '6':
textBox1.Text += "6";
break;
case '7':
textBox1.Text += "7";
break;
case '8':
textBox1.Text += "8";
break;
case '9':
textBox1.Text += "9";
break;
case '.':
textBox1.Text += ".";
break;
}
e.Handled = true;
}

让窗体的加载事件如下所示。

private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
}

旧答案

您所要做的就是在表单上创建按键事件,如下所示。

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1')
{
btn1_Click(null, null);
}
else if (e.KeyChar == '2')
{
btn2_Click(null, null);
}
//Go write your code with else if.........
}

然后,由于您希望捕获 KeyPress 事件,只要焦点在窗体中,下面的代码会将上述 KeyPress 事件添加到窗体上的所有控件中,以便您可以在窗体中焦点所在的任何位置捕获 KeyPress 事件。

private void Form1_Load(object sender, EventArgs e)
{
foreach (Control ctrl in Controls)
{
ctrl.KeyPress += Form1_KeyPress;
}
}

正如 @Rufus L 在他的回答中提到的,您可以只使用 KeyPreview 属性,该属性将在实际控件收到以下代码之前捕获其他控件的 KeyPress 事件。

private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
}

最新更新