nodejs keydown/keyup事件 [英] nodejs keydown/keyup events
问题描述
我感兴趣的是查看是否可以将功能绑定到用户按下/释放键盘上的键的方式.
I'm interested in seeing if it's possible to bind functions to a user pressing/releasing a key on the keyboard.
到目前为止,我已经能够使用 keypress 模块和 process.stdin
的原始模式:
So far, I've been able to get key press events with the keypress module and process.stdin
's raw mode:
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();
捕获键盘按键并释放事件甚至可以在终端中进行吗?
Are capturing keyboard press and release events even possible in a terminal?
值得注意的是,我对任何浏览器实现都不感兴趣;我正在寻找可以在终端的NodeJS中运行的东西.
It should be worth noting that I am not interested in any browser implementations; I am looking for something that runs in NodeJS in a terminal.
谢谢.
推荐答案
所以我想出了一种解决方法,以限制 stdin
的局限性.
So I figured a workaround the limitations of stdin
to get this to work.
基本上,我使用SDL库(及其节点绑定)在以下位置运行程序在键盘上侦听输入的背景.
Basically I use the SDL library (along with its node bindings) to run a program in the background that listens on the keyboard for input.
要这样做:
- 确保您正在运行节点版本〜0.10.(显然,在0.11上,节点上C绑定的工作方式有些不同吗?)
- 通过自制程序(在Mac上)安装
sdl
,sdl_ttf
和sdl_image
-
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_PollEvent
requires SDL be initialized with SDL_INIT_VIDEO
, which in the script above (on a mac) starts a separate application in the dock that draws nothing, but needs to be focused to accept input.
虽然从技术上讲ANSI终端根本不支持按键事件,但这种解决方法完全可以让Node中的一个按键事件(尽管需要某些基于GUI的系统才能运行,即很可能无法在ssh上运行).
While it's technically true that ANSI terminals simply do not support keyup events, this workaround totally lets one grab keyup events in Node (albeit requiring some GUI-based system to function, i.e. most likely will not work over ssh).
这篇关于nodejs keydown/keyup事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!