Page 1 of 1

key emulate

Posted: Mon Jul 29, 2013 9:37 pm
by fixstuff555
Hi all,

Anyone done any keyboard emulation with Ruby, and the Win32 api?

In particular, I'd like to send keystrokes to the windows keyboard stream using SendInput in API if possible.

Any ideas on how to do this?

I found this:

http://batchloaf.wordpress.com/2012/04/17/simulating-a-keystroke-in-win32-c-or-c-using-sendinput/, but its for C++. so I found this:

http://www.velocityreviews.com/forums/t821631-ruby-dl-sendinput.html

But its not functional the way its shown.. Any ideas on how to do this? I have attached the code I was testing, but I can't get it to work. I'm sure its something stupid.

Re: key emulate

Posted: Tue Jul 30, 2013 4:27 am
by Tronic
this is the code that I use.
:arrow:

Code: Select all

###########################
# Ruby Key Sender by Tronic
###########################

require 'Win32API'
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms646306(v=vs.85).aspx
MapVirtualKey = Win32API.new('user32.dll', 'MapVirtualKey', %w(i i), 'i')

# http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx
SendInput = Win32API.new("user32", "SendInput", %w(i p i), 'i')

# http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270(v=vs.85).aspx
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271(v=vs.85).aspx
INPUT_KEYBOARD = 1
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_KEYUP = 2
# Defined costant for Shift & Ctrl
# Add here the other special key you need
VK_SHIFT = 0x10
VK_CONTROL = 0x11

# Perform the operation hit for the specified key on the keyboard.
# Vkey Specifies an array of key code of the key that hit at the same time.
# For example, if you want to enter the t (lower case)
# keys_send (['T'])
# If you want to enter the T (upper case)
# keys_send ([VK_SHIFT, 'T'])

def keys_send(keys)
# convert key to integer unicode
key_conv= keys.map{|ikeys|
         case ikeys
           when String
           ikeys.unpack('U')[0]
           else
           ikeys
           end   }

wscans = key_conv.map{|vkey| MapVirtualKey.call(vkey, 0)}      
vkeywscan = key_conv.zip(wscans)
 
keydowns = vkeywscan.map{|vkey, wscan|
         [INPUT_KEYBOARD, vkey, wscan, 0, 0, 0, 0, 0].pack('ISSIIIII')
         }
keyups = vkeywscan.map{|vkey, wscan|
         [INPUT_KEYBOARD, vkey, wscan, KEYEVENTF_UNICODE|KEYEVENTF_KEYUP, 0, 0, 0, 0].pack('ISSIIIII')
         }.reverse
 
SendInput.call(keys.length*2, keydowns.join('')+keyups.join(''), keydowns[0].length)
end

 
def event i
   keys_send([VK_SHIFT,'K'])
end

Re: key emulate

Posted: Tue Jul 30, 2013 11:04 am
by MyCo

Re: key emulate

Posted: Tue Jul 30, 2013 12:15 pm
by kortezzzz
THANKS,
and MyCo, please check your massage box.

Re: key emulate

Posted: Tue Jul 30, 2013 3:56 pm
by fixstuff555
Those are awesome guys. Thanks a bunch :)