Smart supports normal keyboard events for all HTML elements that triggers them. It can be confusing since we bolted the events into TW3CustomControl – which gives the impression that you can catch events from everything. Sadly this is not the case (support varies between browsers – and there is the technicality of “setfocus” which is not consistent under browsers. A native call to alert for instance, breaks the focus cycle that we take for granted in native applications).
I wanted to share how you can hook into the global keyboard event chain of the window object. This is of-course a must for games and multimedia designed for the desktop rather than touch devices. You also want to catch and buffer the key-presses to make your games respond as quickly as possible.
In this example we are going to setup the event handler inside a form. If you use multiple forms in your app but want to isolate keyboard handling handling on a global scale, then you should move this code to your application class rather than the form. Either way, here is how you can do it:
// We start off by binding our handler to the event.
// In this case we bind to the window handle.
// Here we catch the JS event, extract the event value we want
// And ship it off to our handler. In a game, I would handle the
// key here since the extra call adds overhead. Every CPU cycle
// counts in the world of HTML5 programming.
@mCode = event.keyCode;
(* As an alternative, you can also access JS objects via a variant,
which is a neat way of getting access to the native JS object
asm @mEvent = event; end;
case mEvent.keyCode of
//do your thing here
// This is basically the standard onKeyDown event handler that
// all Smart components have. But by rule only input elements
// actually bouble this event. So for games and fullscreen apps
// it makes sense to centralize handling in one place.
If you want the other events, like onKeyPress – simply look at how TW3CustomControl does it (w3components.pas unit). All event handling methods are prefixed with CB (callback). Just copy the code into your form or app unit and adapt it. The keyboard events will be added to TW3CustomApplication in the next release.