foxtdev
foxtdev

Reputation: 188

How to check if a key is pressed in Electron?

Is it possible to check if a key is pressed in Electron? I'm not asking to detect when a key is pressed.

When my app starts, I want to be able to hold shift while it starts, before the window loads, to open a special menu. An example of what I'm looking for is:

app.whenReady().then(() => {
     const win = new BrowserWindow({ show: false })
     win.loadFile("whatever.html")
     // ***
     const openSpecialMenu = keyboard.shiftKeyHeld
     // ***
     // do other stuff
     window.show()
})

Upvotes: 2

Views: 1655

Answers (1)

aabuhijleh
aabuhijleh

Reputation: 2464

I don't know if there's an easy way to do this, but I believe you can do this using native APIs.

On Windows you can use GetKeyState.

On macOS you can use the function described in this answer.

You can then build a native node addon that allows you to use these native APIs in your Electron JavaScript code.

In fact, I found a node module for Windows that does what you need: https://github.com/Zysen/node-asynckeystate

You need to do additional work to support other operating systems.

Upvotes: 2

Related Questions