Last active
December 30, 2017 22:13
-
-
Save sandipchitale/5ea18a00d59d3244c908826b9750a83e to your computer and use it in GitHub Desktop.
Keydisplay bar implementation in Electron app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { BrowserWindow, Menu, MenuItem } = require("electron"); | |
function createWindow() { | |
: | |
: | |
: | |
win = new BrowserWindow({ | |
width: 800, | |
height: 400 | |
}); | |
// and load the index.html of the app. | |
win.loadURL( | |
url.format({ | |
pathname: path.join(__dirname, "index.html"), | |
protocol: "file:", | |
slashes: true | |
}) | |
); | |
const keydisplayScript = ` | |
(function(){ | |
var keyDisplayDiv = document.querySelector('#__keydisplay__'); | |
if (keyDisplayDiv) { | |
keyDisplayDiv.parentNode.removeChild(keyDisplayDiv); | |
document.removeEventListener('keyup', document.__keydisplay__, false); | |
return; | |
} | |
keyDisplayDiv = document.createElement('div'); | |
keyDisplayDiv.id = '__keydisplay__'; | |
keyDisplayDiv.style = 'position: fixed;' | |
+ 'height: 50px;' | |
+ 'left: 0;' | |
+ 'bottom: 0;' | |
+ 'right: 0;' | |
+ 'z-index: 10000;' | |
+ 'background-color: rgba(0,0,0,0.8);' | |
+ 'color: white;' | |
+ 'font-size: 36px;' | |
+ 'font-family: monospace;' | |
+ 'text-align: center;' | |
+ 'overflow: hidden;' | |
+ 'margin: auto auto;' | |
+ 'padding-top: 7px;' | |
+ 'user-select: none;'; | |
document.body.appendChild(keyDisplayDiv); | |
document.__keydisplay__ = function(event) { | |
if (event.key !== 'Control' && event.key !== 'Shift' && event.key !== 'Alt' && event.key !== 'Meta') { | |
let keyString = ''; | |
if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey || (event.key && event.key.length > 1)) { | |
if (event.ctrlKey) keyString += 'Ctrl+'; | |
if (event.altKey) keyString += 'Alt+'; | |
if (event.shiftKey) keyString += 'Shift+'; | |
if (event.metaKey) keyString += 'Meta+'; | |
keyString += event.key.replace(/([A-Z])/g, ' $1').replace(/^ /, ''); | |
} | |
keyDisplayDiv.innerText = keyString; | |
} | |
}; | |
document.addEventListener('keyup', document.__keydisplay__, false); | |
})(); | |
`; | |
const menu = new Menu(); | |
menu.append( | |
new MenuItem({ | |
label: "Toggle Keydisplay", | |
accelerator: "CmdOrCtrl+Shift+Alt+k", | |
click: () => { | |
win.webContents.executeJavaScript(keydisplayScript); | |
} | |
}) | |
); | |
: | |
: | |
: | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment