From 62729cbbc786943eff6093ceb4b13146470295ec Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Mon, 27 Aug 2018 17:06:07 +0200 Subject: KeyboardSimulator: Add `simpleKeyPressWithKey:` method This as yet untested method will be responsible for simulating a key press given a single-character string corresponding to the glyph of the key to be pressed. It relies on `keyCodeForChar:` to get the `CGKeyCode` corresponding to the glyph, a method which is currently just a placeholder. --- DomeKey/KeyboardSimulator.h | 3 +++ DomeKey/KeyboardSimulator.m | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/DomeKey/KeyboardSimulator.h b/DomeKey/KeyboardSimulator.h index bdd62b5..dc471d3 100644 --- a/DomeKey/KeyboardSimulator.h +++ b/DomeKey/KeyboardSimulator.h @@ -10,4 +10,7 @@ @interface KeyboardSimulator : NSObject ++ (CGKeyCode)keyCodeForChar:(NSString *)aChar; ++ (void)simpleKeyPressWithKey:(NSString *)aChar; + @end diff --git a/DomeKey/KeyboardSimulator.m b/DomeKey/KeyboardSimulator.m index f33601a..2fa808d 100644 --- a/DomeKey/KeyboardSimulator.m +++ b/DomeKey/KeyboardSimulator.m @@ -10,4 +10,28 @@ @implementation KeyboardSimulator ++ (CGKeyCode)keyCodeForChar:(NSString *)aChar +{ + return (CGKeyCode)0; +} + ++ (void)simpleKeyPressWithKey:(NSString *)aChar +{ + CGEventSourceRef source = CGEventSourceCreate( + kCGEventSourceStateHIDSystemState + ); + + CGKeyCode key_code = [self keyCodeForChar:aChar]; + + CGEventRef key_down = CGEventCreateKeyboardEvent(source, key_code, true); + CGEventRef key_up = CGEventCreateKeyboardEvent(source, key_code, false); + + CGEventPost(kCGHIDEventTap, key_down); + CGEventPost(kCGHIDEventTap, key_up); + + CFRelease(key_down); + CFRelease(key_up); + CFRelease(source); +} + @end -- cgit v1.2.3