Can we check if keys pressed and Which keys were pressed?

I'm not a professional program just a hobbiest who h as done applescripting on and off for fun and to make useful utilities for my computer.

But i've never done any script with Keyboard input. Does applescript do key input scripts?

like for example when the scrip starts , can it check if user presses the A key or the B key or whatever?

How would i do it? I'm on Macos X 10.9.5

Posted on Jan 4, 2015 6:43 PM

Reply
3 replies

Jan 5, 2015 10:23 AM in response to jonsondonson

Hello


You may try something like this. It will work under OS X 10.5 through 10.9.



--APPLESCRIPT return keys_pressed() on keys_pressed() do shell script "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -w <<'EOF' require 'osx/cocoa' include OSX # get keys cc = (0x00..0x7f).select {|vk| CGEventSourceKeyState(KCGEventSourceStateHIDSystemState, vk)}.inject([]) do |a, vk| ev = CGEventCreateKeyboardEvent(nil, vk, true) # vk down begin a << NSEvent.eventWithCGEvent(ev).charactersIgnoringModifiers.to_s rescue end a end # get modifiers m = CGEventSourceFlagsState(KCGEventSourceStateHIDSystemState) mods = { KCGEventFlagMaskAlphaShift => 'capslock', KCGEventFlagMaskShift => 'shift', KCGEventFlagMaskControl => 'control', KCGEventFlagMaskAlternate => 'option', KCGEventFlagMaskCommand => 'command', } mm = mods.keys.sort.inject([]) {|a, k| m & k !=0 ? a << mods[k] : a} print %[%s\\0] % cc.join('') print %[%s\\0] % mm.join(' ') EOF" set r to result set {astid0, AppleScript's text item delimiters} to {AppleScript's text item delimiters, character id 0} set {k, m} to r's text items set AppleScript's text item delimiters to astid0 return {string:k, modifiers:m} end keys_pressed --END OF APPLESCRIPT


Tested under OS X 10.6.8.


Hope this may help,

H



PS. Under OS X 10.10, You'd need to manually install RubyCocoa 1.2.0 which supports Ruby 2.0 or later.


http://rubycocoa.sourceforge.net/

http://sourceforge.net/projects/rubycocoa/files/RubyCocoa/1.2.0/


and change the ruby interpreter in script to


/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Can we check if keys pressed and Which keys were pressed?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.