如何使用Win32 :: Console读取特殊键?

时间:2012-04-16 10:15:06

标签: perl terminal

当我按下Up - 键时,此脚本(Term::TermKey)会输出You pressed: <Up>

#!/usr/bin/env perl
use warnings;
use 5.012;
use Term::TermKey;

my $tk = Term::TermKey->new( \*STDIN );
say "Press any key";
$tk->waitkey( my $key );
say "You pressed: <" . $tk->format_key( $key, 0 ) . ">";

如何使用Win32::Console获得相同的结果?
我试过这个,但它只适用于&#34; normal&#34; lk等关键字,但不包含UpDelete等关键字,...

use Win32::Console;

my $in = Win32::Console->new(STD_INPUT_HANDLE);
$in->Mode(ENABLE_PROCESSED_INPUT);
my $result = $in->InputChar(1);
say "<$result>";

我如何使用Up创建DeleteWin32::Console等工作密钥?

1 个答案:

答案 0 :(得分:4)

向上键不会产生字符。 InputChar无法退货。您需要使用Input

my $con_in = Win32::Console->new(STD_INPUT_HANDLE);
for (;;) {
   my @event = $con_in->Input();

   my $event_type = shift(@event);
   next if !defined($event_type) || $event_type != 1;  # 1: Keyboard

   my ($key_down, $repeat_count, $vkcode, $vscode, $char, $ctrl_key_state) = @event;
   if ($vkcode == VK_UP && ($ctrl_key_state & SHIFTED_MASK) == 0) {
      if ($key_down) {
         say "<Up> pressed/held down" for 1..$repeat_count;
      } else {
         say "<Up> released";
      }
   }
}

有关键盘事件的详情,请参阅KEY_EVENT_RECORD

请参阅Virtual-Key Codes以确定密钥。


上述代码的标题和定义:

use strict;
use warnings;
use feature qw( say );

use Win32::Console qw( STD_INPUT_HANDLE );

use constant {
   RIGHT_ALT_PRESSED  => 0x0001,
   LEFT_ALT_PRESSED   => 0x0002,
   RIGHT_CTRL_PRESSED => 0x0004,
   LEFT_CTRL_PRESSED  => 0x0008,
   SHIFT_PRESSED      => 0x0010,

   VK_UP => 0x26,
};

use constant SHIFTED_MASK =>
   RIGHT_ALT_PRESSED |
   LEFT_ALT_PRESSED |
   RIGHT_CTRL_PRESSED |
   LEFT_CTRL_PRESSED |
   SHIFT_PRESSED;