C#中的数字键代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10626626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Numpad key codes in C#
提问by ALI VOJDANIANARDAKANI
I use these following codes to work with numpad keys.
我使用以下这些代码来处理小键盘键。
if (e.KeyCode == Keys.NumPad0 || e.KeyCode == Keys.D0)
{
MessageBox.Show("You have pressed numpad0");
}
if (e.KeyCode == Keys.NumPad1 || e.KeyCode == Keys.D1)
{
MessageBox.Show("You have pressed numpad1");
}
And also for the other numpad keys. But I want to know how I can to this for "+" , "*" , "/" , " -" , " . " which located next to the numpad keys.
以及其他数字键盘键。但我想知道如何处理 "+" 、 "*" 、 "/" 、 " -" 、 " . " ,它们位于小键盘键旁边。
Thanks in advance
提前致谢
采纳答案by ALI VOJDANIANARDAKANI
For "+" , "*" , "/" , we can use KeyDown event and for "-" , "." we can use KeyPress event.
对于 "+" 、 "*" 、 "/" ,我们可以使用 KeyDown 事件,对于 "-" 、 "." ,我们可以使用 KeyDown 事件。我们可以使用 KeyPress 事件。
Here are the codes :
以下是代码:
private void button1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add)
{
MessageBox.Show("You have Pressed '+'");
}
else if (e.KeyCode == Keys.Divide)
{
MessageBox.Show("You have Pressed '/'");
}
else if (e.KeyCode == Keys.Multiply)
{
MessageBox.Show("You have Pressed '*'");
}
}
private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '.')
{
MessageBox.Show("You have pressed '.'");
}
else if (e.KeyChar == '-')
{
MessageBox.Show("You have pressed '-'");
}
}
回答by zmbq
回答by MinusZero
I used switchto make mine work.
我曾经switch让我的工作。
I am making a calculator and created a KeyDown even on the target textbox. I then used:
我正在制作一个计算器,甚至在目标文本框上也创建了一个 KeyDown。然后我使用了:
switch (e.KeyCode)
{
case Keys.NumPad1:
tbxDisplay.Text = tbxDisplay.Text + "1";
break;
case Keys.NumPad2:
tbxDisplay.Text = tbxDisplay.Text + "2";
break;
case Keys.NumPad3:
tbxDisplay.Text = tbxDisplay.Text + "3";
break;
}
etc.
等等。
The other thing to consider is that if the user then clicked an on screen button, the focus would be lost from the textbox and the key entries would no longer work. But thats easy fixed with a .focus() on the buttons.
另一件要考虑的事情是,如果用户然后单击屏幕上的按钮,焦点将从文本框中丢失并且键条目将不再起作用。但这很容易通过按钮上的 .focus() 修复。

