emscripten-ports / SDL2

Other
166 stars 64 forks source link

Send a keyboard button press through a js function #144

Open ericoporto opened 3 years ago

ericoporto commented 3 years ago

Hi,

I would like to send a key like f12 or alt+enter to my Emscripten built engine from a JS function. The reason is these are buttons that do special things in the engine, but they aren't easily available on the phones, so I would like to place a little overlay with some screen buttons in the html that would send these button presses to the engine.

Is there an easy way to leverage the SDL2 port to do this?

Daft-Freak commented 3 years ago

Should be able to use dispatchEvent from JS, I think:

document.getElementById("canvas").dispatchEvent(new KeyboardEvent("keydown", {keyCode: 0x7B/*F12*/}));
//... and/or "keyup"

(Currently still relying on the old keyCode property)

Might need to manually keydown/up Alt, instead of using altKey though...

ericoporto commented 3 years ago

Thanks, that solves for me!

ericoporto commented 3 years ago

Turns out this dispatchEvent didn't work. :/

The below works for some keys, but I can't find a way to pass the alt key.

window.dispatchEvent(new KeyboardEvent("keydown", {keyCode: 0x7B/*F12*/}));

What should be the alt keyCode?