How to read in special keys with Win32::Console?

后端 未结 1 350
不思量自难忘°
不思量自难忘° 2021-01-20 02:50

When I press the Up-key, this script (Term::TermKey) outputs You pressed: .

#!/usr/bin/env perl
use warnings;
use 5.012;         


        
相关标签:
1条回答
  • 2021-01-20 03:35

    The up key does not result in a character. InputChar cannot possible return it. You need to use 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";
          }
       }
    }
    

    See KEY_EVENT_RECORD for more information about keyboard events.

    See Virtual-Key Codes to identify keys.


    Headers and definitions for above code:

    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;
    
    0 讨论(0)
提交回复
热议问题