Anders Sewerin Johansen
Anders Sewerin Johansen

Reputation: 1666

Simulate keystrokes in OS X for stress testing?

I want to make a simple program that sends random keystrokes to my other application (a simple text editor). The purpose is to stress test the other app by feeding it either random letters or a large prepared text.

What I need is a way to convert a character in an NSString to a keycode, so I can pass it to the OS thus:

CGKeyCode code = [self convertLetter:myOneCharNSString];
CGEventRef e = CGEventCreateKeyboardEvent (NULL, code, true);
CGEventPost(kCGSessionEventTap, e);
CFRelease(e);

Any clues?

Upvotes: 2

Views: 273

Answers (2)

Anders Sewerin Johansen
Anders Sewerin Johansen

Reputation: 1666

This will do the trick:

-(void) fakeAnUnicharWithString : (NSString*) characters
{
    CGEventSourceRef eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); 
    CGEventRef keyEventDown = CGEventCreateKeyboardEvent(eventSource, 0, true); 
    UniChar buffer;
    for (int i = 0; i < [characters length]; i++) {
        [characters getCharacters:&buffer range:NSMakeRange(i, 1)];
        keyEventDown = CGEventCreateKeyboardEvent(eventSource, 1, true);
        CGEventKeyboardSetUnicodeString(keyEventDown, 1, &buffer);
        CGEventPost(kCGHIDEventTap, keyEventDown);
        CFRelease(keyEventDown);
    }
    CFRelease(eventSource);
}

Upvotes: 3

Anders Sewerin Johansen
Anders Sewerin Johansen

Reputation: 1666

I ended up modifying parts of the Shortcut Recorder project (http://code.google.com/p/shortcutrecorder/). It was a bit tricky, but in the end I prevailed. Too bad that the stress test didn't shake out the bugs I had hoped for, but at least now I have the tool for future reference.

Upvotes: 1

Related Questions