在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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句