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(); } 

5 Answers 5

9

Use keypress event like this:

private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyCode == Keys.F1 && e.Alt) { //do something } } 
Sign up to request clarification or add additional context in comments.

2 Comments

...Are you sure that should be one =? Also, I don't think you need the extra surrounding parentheses.
Pretty sure the == sign refers to checking equality rather than assignment.
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) } } 

Comments

1

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

Comments

1

Try to use the KeyDown event.

Just see KeyDown in MSDN

1 Comment

Not exactly what i was looking for. Thanks anyways!
1

Just do

if (Input.GetKeyDown("/* KEYCODE HERE */")) { /* CODE HERE */ } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.