Skip to content

Instantly share code, notes, and snippets.

@thomasjslone
Last active June 4, 2016 05:15
Show Gist options
  • Save thomasjslone/7a1aa4a829c01596e45ac01035f8a329 to your computer and use it in GitHub Desktop.
Save thomasjslone/7a1aa4a829c01596e45ac01035f8a329 to your computer and use it in GitHub Desktop.
## Creates a stream array of key press instances, updates 100 times a second, ignores held keys(not totaly working yet)
## This is a pure ruby key listener / logger that works for the consols keyboard context, unfortuanatly not in other contexts
## such as other windows.
##
## Currently a bug is causing every loop to set the current value to lift even if key press is still present
## this bug is in the listen loop and is involved with the onditional branch that is supposed to set lift status
## when a check reveals that no key is being pressed, this will allow the stream to capture individual instances
## of key presses, the current variable represents the current key being pressed and is accurate with in a
## ten-thoudanth of a second, to change this you can tweak the sleep setting.
##
## I will fix this crap class when I get the time but if you feel like you're upto it, please feel free to give it a shot.
##
class KeyPress_Stream
def initialize
@stream = []
@current = "lift"
@listen = false
@use_stty = nil
begin
require 'Win32API'
@kbhit = Win32API.new('crtdll', '_kbhit', [ ], 'I')
@getch = Win32API.new('crtdll', '_getch', [ ], 'L')
@use_stty = false
rescue LoadError
@use_stty = true
end
listen
end
def listen
@listen = true
while @listen
k = self.getkey.to_i.chr.to_s
if k.to_s != "" or k != nil
@current = k.to_s
if @stream[-1].to_s != @current.to_s
@stream << @current.to_s
end
puts "Key Pressed: " + @stream.to_s
else
@current = "lift"
end
sleep 0.01
end
end
def getkey
if @use_stty
char = nil
begin
system('stty raw -echo')
char = (SDTIN.read_nonblock(1).ord rescue nil)
ensure
system('stty -raw echo')
end
return char
else
return @kbhit.Call.zero? ? nil : @getch.Call
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment