- Home /
Is there a way to program global hotkeys in your game?
I want to add global hotkeys to my game (I don't mean the unity editor hotkeys), so that if the game windows loses focus you can still press a key combination to activate some function in your script.
Does anyone know if this is possible (and maybe how :P)?
Answer by Bunny83 · Apr 20, 2016 at 12:11 AM
That's not possible with Unity's built-in API. Keep in mind it's a game engine in the first place. Which application receives keyboard input is determined by the OS. Normal applications (which includes games) should not react to any kind of input when they don't have the focus.
Some special applications might require system-wide hotkeys, but those can only be achieves by directly working together with the OS. So any solution will be platform specific.
On windows you have several posibilities. In an event driven environment like windoes you usually want to register an keyboard hook. However keyboard hooks need to be implemented in a native DLL as the dll will be injected into other applications in order to receive the events. With Unity this approach would be difficult since you can't react to custom window messages as Unity itself handles them for your application.
Another way is to poll the key / keyboard state using either GetKeyState or GetKeyboardState. With GetKeyState you can query a single virtual key and GetKeyboardState reads the state of all 256 virtual keys at once into an array. Keep in mind those a native code methods so you would need to import those method using a pInvoke signature. Also keep in mind that polling the keyboard has a chance of missing some very short keypresses. Oh and don't forget to make your application to run in background
Thanks for the feedback, I'm running windows. I'll give the Get$$anonymous$$eyState a try :D