Thursday, September 6, 2007

Ruby Capture Key Presses - getc doesn't work

Problem: (doesn't work)
while true
ch = getc #return immediately the key I just pressed (enter, a, down arrow)
puts ch
end

In an almost religious pursuit of ways of capturing keypresses in ruby (for windows) I found a few different technologies that help.

Solution 1 (curses): works! except arrow keys
require 'curses'

#stdscr.keypad(true) # would be great if this was implemented for windows
while true
ch = Curses.getch
puts ch
end

* keypad(true) isn't implemented on windows

Solution 2: Using win32 api
require 'Win32API'

$win32_console_kbhit = Win32API.new("msvcrt", "_kbhit", [], 'I')
$win32_console_cputs = Win32API.new("msvcrt", "_cputs", ['P'], 'I')
$win32_console_getch = Win32API.new("msvcrt", "_getch", [], 'I')

def console_input_ready?
$win32_console_kbhit.call != 0
end

def console_input
$win32_console_getch.call
end

def console_output( str )
$win32_console_cputs.call( str )
end

while true
if console_input_ready? then
ch = console_input
puts "ch: #{ch.chr}"
end
end

And this works for arrow keys so I am happy

No comments: