Detecting key presses in FLTK
Global shortcut handler
See section 6 of the FLTK online manual
Add an event handler function like this to your code:
int keyhandler(int event) {
if (event == FL_SHORTCUT) {
if (Fl::event_key() == 'y') {
//do something because the y key was pressed
return 1; // to indicate we used the key event
} // here you can test for other keys, as wanted
}
return 0; // we had no interest in the event
}
Then hook this function into the event handling loop with
a line like this, just before calling Fl::run()
Fl::add_handler(keyhandler);
There are other events you might look for: separate key up and key down events,
for example. However, this global handler can't see all events, for example
KeyUp events (when a key is released). There are other ways of doing this:
Other possibilities
- Subclass your main window, or the widget inside it that you want to see the
keys, and implement the handle() method in the derived class, see FLTK manual
chapter 7 and appendix C
- Provide a new dummy widget which doesn't appear on the screen, but has the
job of handling all keyboard events. A simple example of this is provided
in this file. It illustrates
capturing y, n presses (for yes/no), cursor keys and key up events.
- Use the shortcut() method of a button to cause it to be invoked when a key
is pressed