Skip to content

Instantly share code, notes, and snippets.

@claymcleod
Last active August 29, 2015 14:05
Show Gist options
  • Save claymcleod/9d0a0a6eda00e8754546 to your computer and use it in GitHub Desktop.
Save claymcleod/9d0a0a6eda00e8754546 to your computer and use it in GitHub Desktop.
// Title: Sending Keystrokes
// Authors: Clay McLeod
// Description: An example of how to send keystrokes to a window
// Section: Objective-C
// Subsection: System Events
#import "Keystrokes.h"
@implementation Keystrokes
Boolean holdKeyEvent(int keyCode, int minSleepSeconds, int maxSleepSeconds)
{
CGEventRef keyDown = CGEventCreateKeyboardEvent(kCGEventSourceStateCombinedSessionState,((CGKeyCode)(keyCode)),true);
CGEventRef keyUp = CGEventCreateKeyboardEvent(kCGEventSourceStateCombinedSessionState,((CGKeyCode)(keyCode)),false);
if(keyUp == NULL || keyDown == NULL) return false;
CGEventPost(kCGHIDEventTap,keyDown);
float diff = maxSleepSeconds - minSleepSeconds;
float someFloat = (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + minSleepSeconds;
NSLog(@"Holding Key Code %d for %f seconds", keyCode, (float)someFloat);
usleep(someFloat * 1000000);
CGEventPost(kCGHIDEventTap,keyUp);
CFRelease(keyDown);
CFRelease(keyUp);
return true;
}
@end
#import <Foundation/Foundation.h>
@interface Keystrokes : NSObject
Boolean holdKeyEvent(int keyCode, int minSleepSeconds, int maxSleepSeconds);
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment