Harry, I have tried HighLine but that’s not what I want (or am I making
a
mistake here?). I am trying to solve the problem - ** “Display series of
numbers (1,2,3,4, 5….etc) in an infinite loop. The program should quit
if
someone hits a specific key (Say ESCAPE key).”
Somehow I want to keep checking in a thread (this should be
non-blocking)
for the ESC key press. Once ESC is pressed my program terminates. Right
now,
my thread code blocks till I press ESC key, as you can see here -
require ‘Win32API’
def getchar
char = Win32API.new(“crtdll”, “_getch”, [], ‘L’).call
if char == 27 # ESC key
exit
end
end
Change your operating system, or don’t use threads with blocking
keyboard I/O. It doesn’t work on Windows. For your code above (which
doesn’t use threads) you could call the Win32 function “_kbhit” before
calling “_getch”. In a thread you could do the same in a busy loop, but
don’t forget to sleep a little bit inside the loop.
C:\family\ruby\key_press>cat -n a1d.rb
1 #------------------------------
2 require ‘Win32API’
3
4 @@kbhit = Win32API.new(“msvcrt”, “_kbhit”, [], ‘I’)
5 @@getch = Win32API.new(“msvcrt”, “_getch”, [], ‘I’)
6
7 def capture_key
8 unless @@kbhit.call.zero?
9 yield @@getch.call
10 end
11 end
12
13 KEY_Esc = 27
14 $stdout.sync=true
15
16 i=0
17 loop do
18 capture_key do |key|
19 puts “keypressed: value #{key}, char #{key.chr}” if $DEBUG
20 if key == KEY_Esc
21 puts “Escaping key pressed. Exiting…” if $DEBUG
22 exit
23 end
24 end
25 sleep 1 #delay it since it’s too fast
26 puts “#{i+=1}”
27 end
28 #------------------------------
C:\family\ruby\key_press>ruby -d a1d.rb
1
2
3
4
keypressed: value 117, char u
5
keypressed: value 101, char e
6
7
8
keypressed: value 119, char w
9
10
keypressed: value 120, char x
11
12
keypressed: value 27, char ?
Escaping key pressed. Exiting…
C:\family\ruby\key_press>
Hth.
kind regards -botp
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.