在 Perl/Tk 中,可以像这样绑定事件:
$mw->bind('<KeyPress-W>', sub{print "W is pressed";});
是否有可能从另一个方向获得这些信息?我可以拨打“获取按键状态”或“检查是否按下 W”之类的电话吗?
它不会直接对事件做出反应。
当然,有可能为各种事件填充变量,但我想知道是否有这样的方法。
Perl/Tk 不提供这样的功能。因此,您必须自己跟踪事件。请注意,有Any-KeyPress
andAny-KeyRelease
事件,因此您不必为每个键创建绑定:
$mw->bind("<Any-KeyPress>" => sub {
warn $_[0]->XEvent->K; # prints keysym
});
如果您使用的是 X11,那么使用该X11::Protocol
模块(可以在 Perl/Tk 脚本中使用)并调用该QueryKeymap
方法将为您提供实际按下的键码。这是一个小脚本,它演示了这一点:
use strict;
use X11::Protocol;
# Get the keycode-to-keysym mapping. Being lazy, I just parse
# the output of xmodmap -pke. The "real" approach would be to
# use X11 functions like GetKeyboardMapping() and the
# X11::Keysyms module.
my %keycode_to_keysym;
{
open my $fh, "-|", "xmodmap", "-pke" or die $!;
while(<$fh>) {
chomp;
if (m{^keycode\s+(\d+)\s*=(?:\s*(\S+))?}) {
if (defined $2) {
$keycode_to_keysym{$1} = $2;
}
} else {
warn "Cannot parse $_";
}
}
}
my $x11 = X11::Protocol->new;
while(1) {
my $keyvec = $x11->QueryKeymap;
for my $bit (0 .. 32*8-1) {
if (vec $keyvec, $bit, 1) {
warn "Active key: keycode $bit, keysym $keycode_to_keysym{$bit}\n";
}
}
sleep 1;
}