我感兴趣的是看看是否有可能将函数绑定到用户按下/释放键盘上的键。
到目前为止,我已经能够获得键压模块和process.stdin的原始模式的关键新闻事件:
var keypress = require('keypress');
keypress(process.stdin);
process.stdin.on('keypress', function(ch, key) {
console.log('got "keypress"', key);
if (key && key.ctrl && key.name == 'c') {
process.exit();
}
});
process.stdin.setRawMode(true);
process.stdin.resume();在终端中是否有可能捕获键盘、按下和释放事件?
值得注意的是,我对任何浏览器实现都不感兴趣;我正在寻找在终端中运行在NodeJS中的东西。
谢谢大家。
发布于 2014-04-27 10:13:35
因此,我想出了一个解决办法,解决了stdin的局限性,使其能够正常工作。
基本上,我使用SDL库(以及它的节点绑定)在后台运行一个程序,在键盘上监听输入。
为此,请执行以下操作:
sdl、sdl_ttf和sdl_image (在mac上)npm install --save https://github.com/creationix/node-sdl/tarball/master然后是这样的东西:
var sdl = require('sdl');
sdl.init(sdl.INIT.VIDEO);
while (true) {
var e;
while (e = sdl.pollEvent()) {
console.log(e);
}
}SDL_PollEvent需要用SDL_INIT_VIDEO初始化SDL,在上面的脚本(在mac上)中,SDL在码头上启动一个单独的应用程序,它没有绘制任何内容,但是需要集中精力接受输入。
虽然ANSI终端在技术上确实不支持keyup事件,但这个解决方案完全允许一个人在Node中捕获密钥事件(尽管需要一些基于GUI的系统才能工作,也就是说,很可能不会在ssh上工作)。
发布于 2016-12-15 07:48:51
在Linux桌面上,您可以将'xev‘命令的输出传输到模块中,然后解析流以发出您自己的'keyup’和'keydown‘事件。可能不如SDL那么便携,但更简单。有一个模块来做这件事。(免责声明:我写的)。
const xevEmitter = require('xev-emitter')(process.stdin)
xevEmitter.on('KeyPress', (key) => {
console.log(key, 'was pressed')
})
xevEmitter.on('KeyRelease', (key) => {
console.log(key, 'was released')
})执行:
$ xev | node example.js
h was pressed
h was released发布于 2020-04-27 02:45:57
这是一个很好的工具:https://www.npmjs.com/package/iohook
查看示例代码:
npm install iohook
const ioHook = require('iohook');
/* In next example we register CTRL+F7 shortcut (in MacOS, for other OS, keycodes can be some different). */
const id = ioHook.registerShortcut([29, 65], (keys) => {
console.log('Shortcut called with keys:', keys)
});
ioHook.on("keydown", event => {
console.log(event);
/* You get object like this
{
shiftKey: true,
altKey: true,
ctrlKey: false,
metaKey: false
keycode: 46,
rawcode: 8,
type: 'keydown'
}
*/
});
//register and start hook
ioHook.start();
// Alternatively, pass true to start in DEBUG mode.
ioHook.start(true);软件包ioHook doc https://wilix-team.github.io/iohook/usage.html的使用链接
https://stackoverflow.com/questions/23317504
复制相似问题