How to capture a key press in Ruby?

送分小仙女□ 提交于 2019-12-06 07:34:03

问题


In Ruby, I need a simple thread that would run some code every time a key in pressed. Is there a way to do that?

I need to be able to capture the Page Up and Page Down

Here is what I tried:

#!/usr/bin/env ruby

Thread.new do
  while c = STDIN.getc
    puts c.chr
  end
end

loop do
  puts Time.new
  sleep 0.7
end

This almost works. There is only 1 issue, one needs to hit return after every key stroke. I guess this is because of buffered IO.


回答1:


You can use the curses library to capture key presses without buffering.

require 'curses'

Curses.noecho # do not show typed keys
Curses.init_screen
Curses.stdscr.keypad(true) # enable arrow keys (required for pageup/down)

loop do
  case Curses.getch
  when Curses::Key::PPAGE
    Curses.setpos(0,0)
    Curses.addstr("Page Up")
  when Curses::Key::NPAGE
    Curses.setpos(0,0)
    Curses.addstr("Page Dn")
  end
end

The key codes are here:

http://ruby-doc.org/stdlib/libdoc/curses/rdoc/index.html

You can find a longer example on github:

https://github.com/grosser/tic_tac_toe/blob/master/bin/tic_tac_toe



来源:https://stackoverflow.com/questions/7297753/how-to-capture-a-key-press-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!