Trying to detect keypress
Asked Answered
A

5

5

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();    
}
Aretta answered 19/10, 2012 at 19:20 Comment(0)
D
9

Use keypress event like this:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyCode == Keys.F1 && e.Alt)
    {
        //do something
    }
}
Disarmament answered 19/10, 2012 at 19:25 Comment(2)
...Are you sure that should be one =? Also, I don't think you need the extra surrounding parentheses.Rimple
Pretty sure the == sign refers to checking equality rather than assignment.Erfert
A
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)
        }
    }
Asteria answered 20/6, 2019 at 16:31 Comment(0)
V
1

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

Vacillate answered 19/10, 2012 at 19:22 Comment(0)
E
1

Try to use the KeyDown event.

Just see KeyDown in MSDN

Evidence answered 19/10, 2012 at 19:26 Comment(1)
Not exactly what i was looking for. Thanks anyways!Aretta
F
1

Just do

if (Input.GetKeyDown("/* KEYCODE HERE */"))
{
    /* CODE HERE */
}
Ferric answered 21/9, 2021 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.