
OpenTK Keyboard Input Example
Posted Thursday, 12 July, 2012 - 17:35 by flopoloco3 different ways of getting key input, each with his benefits.
using System; using OpenTK; using OpenTK.Input; namespace OpenTKKey { class MainClass : GameWindow { // 1. Exit using keyboard event handler // 2. Exit by using method of OpenTK GameWindow // 3. By using the Keyboard property protected override void OnLoad (EventArgs e) { // 1 Keyboard.KeyDown += HandleKeyDown; } // 1 void HandleKeyDown (object sender, KeyboardKeyEventArgs e) { if (e.Key == Key.Escape) Exit (); } // 2 protected override void OnKeyPress (OpenTK.KeyPressEventArgs e) { // This brings this Exact string "Escape" // If you don not want to use Windows.Forms assembly then // check against plain charachters else you do it like this // for type value safety: System.Windows.Forms.Keys.Q if (e.KeyChar == 'q' || e.KeyChar == 'Q') Exit (); } // 3 protected override void OnUpdateFrame (FrameEventArgs e) { if (Keyboard[Key.Space]) Exit (); base.OnUpdateFrame (e); } public static void Main (string[] args) { using (var m = new MainClass()) { m.Run (); } } } }
- flopoloco's blog
- Login or register to post comments


Comments
Re: OpenTK Keyboard Input Example
I am searching how to get the Keyboard device without the GameWindow.
Must be a keyboard instantiation with event handler... Any ideas?
Re: OpenTK Keyboard Input Example
Getting Input while bypassing the 'GameWindow' requires a couple of things...
Firstly, to get input in general, you need to have the respective 'Device' class, so you'll need something like this...
In order to instantiate this class, you have to have access to the 'IInputDriver' from the NativeWindow your project is using. I made a singleton reference to my NativeWindow and grabbed the IInputDriver when i needed it.
After you have all of this, you can add new EventHandlers to the ButtonUp/Down and KeyUp/Down events.
You can also access things like the mouse position and the wheel position from the MouseDevice class.
The main thing to keep in mind is that you'll need to keep a reference to your NativeWindow instance for many reasons (depending on your desired features), so be sure to do so to save yourself a headache.