我编写了一个使用
ffi
、
ref
和
ref-struct
模块在 Windows 上捕获热键的 Node 脚本。但是,由于
ffi
和
ref
是本地插件,所以在打包成 .exe 文件时遇到了一些问题。有关更多信息,请参见我之前开启的这个
GitHub 问题。
无论如何,以下是代码:
var FFI = require('ffi'),
ref = require('ref'),
Struct = require('ref-struct');
var pointStruct = Struct({
'x': 'long',
'y': 'long'
});
var msgStruct = Struct({
'hwnd': 'int32',
'message': 'int32',
'wParam': 'int32',
'lParam': 'int32',
'time': 'int32',
'pt': pointStruct
});
var msgStructPtr = ref.refType(msgStruct);
var user32 = new FFI.Library('user32', {
'RegisterHotKey': [
'bool', ['int32', 'int', 'int32', 'int32']
],
'GetMessageA': [
'bool', [msgStructPtr, 'int32', 'int32', 'int32']
]
var ALT = 0x0001,
CTRL = 0x0002,
SHIFT = 0x0004;
var MEDIA_NEXT = 0xB0,
MEDIA_PREV = 0xB1,
MEDIA_STOP = 0xB2,
MEDIA_PLAY_PAUSE = 0xB3,
MEDIA_LAUNCH = 0xB5;
var PERIOD = 0xBE,
COMMA = 0xBC,
EQUAL = 0xBB,
DIVIDE = 0xBF,
SQUOTE = 0xDE,
PAGEUP = 0x21,
PAGEDOWN = 0x22;
registrations = [];
registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_NEXT));
registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_PREV));
registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_STOP));
registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_PLAY_PAUSE));
registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_LAUNCH));
registrations.push(user32.RegisterHotKey(0, 1, CTRL, PERIOD));
registrations.push(user32.RegisterHotKey(0, 1, CTRL, COMMA));
registrations.push(user32.RegisterHotKey(0, 1, CTRL, EQUAL));
registrations.push(user32.RegisterHotKey(0, 1, CTRL, DIVIDE));
registrations.push(user32.RegisterHotKey(0, 1, CTRL | ALT, PAGEUP));
registrations.push(user32.RegisterHotKey(0, 1, CTRL | ALT, PAGEDOWN));
console.log(registrations);
var myMsg = new msgStruct;
while (user32.GetMessageA(myMsg.ref(), 0, 0, 0)) {
var key = myMsg.lParam >> 16;
switch (key) {
case MEDIA_NEXT: console.log('media next'); break;
case MEDIA_PREV: console.log('media prev'); break;
case MEDIA_STOP: console.log('media stop'); break;
case MEDIA_PLAY_PAUSE: console.log('media play/pause'); break;
case MEDIA_LAUNCH: console.log('media launch'); break;
case PERIOD: console.log('next'); break;
case COMMA: console.log('previous'); break;
case EQUAL: console.log('play/pause'); break;
case DIVIDE: console.log('info'); break;
case PAGEUP: console.log('volume up'); break;
case PAGEDOWN: console.log('volume down'); break;
default: console.log('undefined hotkey', key, key.toString(16));
}
}
如果您希望在node-webkit上使用此功能,请确保使用
nw-gyp 构建所有本机插件,并将 --target 设置为您所使用的node-webkit版本(在我的情况下为0.5.1):
$ nw-gyp clean configure --target=v0.5.1 build
请查阅MSDN文档以了解所使用的方法签名和结构体。希望这能帮到你!