使用Ruby捕获终端中的鼠标事件

7gyucuyw  于 11个月前  发布在  Ruby
关注(0)|答案(1)|浏览(109)

下面是我一直在尝试的一些代码:

print "\e[?1003h"

begin
  loop do
    begin
      input = ARGF.read_nonblock(1024)
      puts "input: #{input.inspect}"
    rescue IO::EAGAINWaitReadable
    end
  end
ensure
  print "\e[?1003l"
end

字符串
当我运行这段代码时,我可以看到这样的内容被打印到终端,但没有一个指示它被发送到ARGF。我也试过STDIN。我的read_nonblock调用总是引发IO::EAGAINWaitReadable,这似乎是预期的行为(参见规范)。

^[[MCn@^[[MCn?^[[MCn>^[[MCm>^[[MCm=^[[MCk;^[[MCk:^[[MCj:^[[MCi:^[[MCh:^[[MCg:^[[MCe:^[[MCd:^[[MCc:^[[MCb;^[[MCb<^[[MCc<^[[MCd<^[[MCe<^[[MCf<^[[MCg<^[[MCg;^[[MCf;^[[MCf:^[[MCe:^[[MCd:^[[MCd;^[[MCd<^[[MCe<^[[MCf<^[[MCg<^[[MCg;^[[MCg<^[[MCg;^[[MCf;^[[MCf:^[[MCe:^[[MCd:^[[MCd;^[[MCe;^[[MCe<^[[MCe;^[[MCf;^[[MCe;^[[MCe:^[[MCe;^[[MCf;^[[MCe;^[[MCd;^[[MCd<^[[MCe<^[[MCe=^[[MCf=^[[MCf<^[[MCe<^[[MCe;^[[MCd;^[[MCc;^[[MCc<^[[MCd<^[[MCe<^[[MCe;^[[MCe<^[[MCf<^[[MCf;^[[MCe;^[[MCd;^[[MCd<^[[MCe<^[[MCe=^[[MCf=^[[MCg=^[[MCh=^[[MCi>^[[MCj>^[[MCk>^[[MCl>^[[MCn?^[[MCpA^[[MCqB^[[MCrC^[[MCrD^[[MCsD^[[MCsE^[[MCtF^[[MCsG^[[MCrG^[[MCqG^[[MCpG^[[MCpH^[[MCmH^[[MCmG^[[MClG^[[MCgI^[[MCfI^[[MCeI^[[MC]I^[[MC\I^[[MC[I

cgyqldqp

cgyqldqp1#

如果你想做你自己的处理,你必须在raw模式下捕获字符。
这应该可以工作:(我试图保持你的代码结构)

require 'io/console'

at_exit { print "\e[?1003l" }

print "\e[?1003h"

STDIN.raw(intr: true) do # raw mode but allow ctrl-c
  loop do
    begin
      input = STDIN.read_nonblock(1024)
      p input: input
    rescue IO::EAGAINWaitReadable
      IO.select([STDIN])
      retry
    end
  end
end

字符串
输出:(移动鼠标时)

$ ruby mouse.rb
{:input=>"\e[MCYB"}
{:input=>"\e[MCZB"}
{:input=>"\e[MC[B"}
{:input=>"\e[MC\\A"}
{:input=>"\e[MC]A"}
{:input=>"\e[MC]B"}
{:input=>"\e[MC\\B"}


当然,您仍然需要以有意义的方式实际处理鼠标输入。

相关问题