如何在飞镖控制台应用程序中收听键盘事件?
How do listen a keyboard event in dart console app?
我找到的关于 web 和 dart:html 包的所有示例。我可以在桌面控制台程序中从系统获取键盘或鼠标事件吗?
我认为您无法读取鼠标事件,但您可以从 stdin
读取按键代码。为此,只需将 lineMode
和 echoMode
都设置为 false
,然后收听此流即可将其切换为 "raw" 模式。
这是一个简单的例子:
import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
Future main() async {
io.stdin
..lineMode = false
..echoMode = false;
StreamSubscription subscription;
subscription = io.stdin.listen((List<int> codes) {
var first = codes.first;
var len = codes.length;
var key;
if (len == 1 && ((first > 0x01 && first < 0x20) || first == 0x7f)) {
// Control code. For example:
// 0x09 - Tab
// 0x10 - Enter
// 0x1b - ESC
if (first == 0x09) {
subscription.cancel();
}
key = codes.toString();
} else if (len > 1 && first == 0x1b) {
// ESC sequence. For example:
// [ 0x1b, 0x5b, 0x41 ] - Up Arrow
// [ 0x1b, 0x5b, 0x42 ] - Down Arrow
// [ 0x1b, 0x5b, 0x43 ] - Right Arrow
// [ 0x1b, 0x5b, 0x44 ] - Left Arrow
key = '${codes.toString()} ESC ${String.fromCharCodes(codes.skip(1))}';
} else {
key = utf8.decode(codes);
}
print(key);
});
print('Start listening');
}
您还可以利用 dart_console
package or adapt their readKey()
解析控制和 esc 代码的方法。
我找到的关于 web 和 dart:html 包的所有示例。我可以在桌面控制台程序中从系统获取键盘或鼠标事件吗?
我认为您无法读取鼠标事件,但您可以从 stdin
读取按键代码。为此,只需将 lineMode
和 echoMode
都设置为 false
,然后收听此流即可将其切换为 "raw" 模式。
这是一个简单的例子:
import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
Future main() async {
io.stdin
..lineMode = false
..echoMode = false;
StreamSubscription subscription;
subscription = io.stdin.listen((List<int> codes) {
var first = codes.first;
var len = codes.length;
var key;
if (len == 1 && ((first > 0x01 && first < 0x20) || first == 0x7f)) {
// Control code. For example:
// 0x09 - Tab
// 0x10 - Enter
// 0x1b - ESC
if (first == 0x09) {
subscription.cancel();
}
key = codes.toString();
} else if (len > 1 && first == 0x1b) {
// ESC sequence. For example:
// [ 0x1b, 0x5b, 0x41 ] - Up Arrow
// [ 0x1b, 0x5b, 0x42 ] - Down Arrow
// [ 0x1b, 0x5b, 0x43 ] - Right Arrow
// [ 0x1b, 0x5b, 0x44 ] - Left Arrow
key = '${codes.toString()} ESC ${String.fromCharCodes(codes.skip(1))}';
} else {
key = utf8.decode(codes);
}
print(key);
});
print('Start listening');
}
您还可以利用 dart_console
package or adapt their readKey()
解析控制和 esc 代码的方法。