blah blah blah is here! blah blah » Close

up1down
link

Hi all,

I'm writing an application for a graphics project using C# and OpenGL library (SharpGL). I want to "listen" to user keyboard input and act accordingly (meaning, if the user presses the "Up" button, I want to move the objects in the app upwards..)

I tried to write the code in Form1_KeyDown event, however I think this is no good since it doesn't catch the keyboard input (I'm kinda new in all this graphics programming, as you can probably see :)

This is the code I have:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up: // if the "/\" key was pressed
lblKeyPressed.Text = "UP";
break;
case Keys.Down: // if the "\/" key was pressed
lblKeyPressed.Text = "DOWN";
break;
... (more buttons to handle)
default: break;
}
}


If anyone could help me in how to read keystrokes and act accordingly, I would be very greatful!

Thx :)

last answered one year ago

1 answers

link

Although there's nothing wrong with your code, to trap keystrokes at the form level you need to set the form's KeyPreview property to true. Otherwise, the keystrokes will go straight to whichever control currently has the input focus.

Incidentally, if after handling a keystroke at the form level, you don't then want to it to be processed by the control which has focus, just set e.Handled to true in the KeyDown eventhandler.

yonifra
18

This is exactly what I needed! Thanks! :)

Feedback