4

I made a method that detects when a key is pressed, but its not working! Heres my code

void KeyDetect(object sender, KeyEventArgs e)
{ 
    if (e.KeyCode == Keys.W && firstload == true)
    {
        MessageBox.Show("Good, now move to that box over to your left");
        firstload = false;
    }
}

I also tried to make a keyeventhandler but, it sais "cannot assign to key detect because it is a method group"

public Gwindow()
{
    this.KeyDetect += new KeyEventHandler(KeyDetect);
    InitializeComponent();    
}
nrofis
  • 8,975
  • 14
  • 58
  • 113
Adam_MOD
  • 65
  • 1
  • 1
  • 5

5 Answers5

9

Use keypress event like this:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyCode == Keys.F1 && e.Alt)
    {
        //do something
    }
}
psyklopz
  • 2,283
  • 4
  • 24
  • 29
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70
  • 1
    ...Are you sure that should be one `=`? Also, I don't think you need the extra surrounding parentheses. – Nic May 26 '15 at 12:10
  • 2
    Pretty sure the `==` sign refers to checking equality rather than assignment. – Ron Zhang Feb 04 '20 at 03:54
6

1) Go to your form's Properties

2) Look for the "Misc" section and make sure "KeyPreview" is set to "True"

3) Go to your form's Events

4) Look for the "Key" section and double click "KeyDown" to generate a function to handle key down events

Here is some example code:

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        Console.WriteLine("You pressed " + e.KeyCode);
        if (e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0)
        {
            //Do Something if the 0 key is pressed (includes Num Pad 0)
        }
    }
Jordan Miller
  • 143
  • 1
  • 9
1

You are looking for this.KeyPress. See How to Handle Keypress Events on MSDN.

Chibueze Opata
  • 9,856
  • 7
  • 42
  • 65
1

Try to use the KeyDown event.

Just see KeyDown in MSDN

nrofis
  • 8,975
  • 14
  • 58
  • 113
1

Just do

if (Input.GetKeyDown("/* KEYCODE HERE */"))
{
    /* CODE HERE */
}
Sergio Carneiro
  • 3,726
  • 4
  • 35
  • 51