Reputation: 2111
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
Upvotes: 6
Views: 37740
Reputation: 115
There is a simple way to learn all the keycodes without checking the manuals.
Create a form and then go to KeyDown event of the form then add this
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString());
}
Then you will get the name of the any key you have pressed on your keyboard
Upvotes: 1
Reputation: 11
I used switch
to make mine work.
I am making a calculator and created a KeyDown even on the target textbox. I then used:
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.
Upvotes: 0
Reputation: 2111
For "+" , "*" , "/" , we can use KeyDown event and for "-" , "." we can use KeyPress event.
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 '-'");
}
}
Upvotes: 6