[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Trapping ESC key

Peña, Botp

3/17/2007 4:22:00 AM

From: I G [mailto:rubycrazy@gmail.com] :
# I am stuck and can't find a simple and portable way to trap
# the ESC key. Any
# pointers, help is most appreciated. The code I have now is -
#
# require 'Win32API'
# def getchar
# char = Win32API.new("crtdll", "_getch", [], 'L').call
# if char == 27 # ESC key
# exit
# end
# end
#
# i = 0
# loop do
# print "#{i+=1}, "
# getchar
# end

can you try this sample?

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