Simulating key press events in Mac OS X

后端 未结 2 1920
心在旅途
心在旅途 2020-11-29 05:00

I\'m writing an app where I need to simulate key press events on a Mac, given a code that represents each key. It seems I need to use the CGEventCreateKeyboardEvent

2条回答
  •  暖寄归人
    2020-11-29 05:18

    Here's code to simulate a Cmd-S action:

    CGKeyCode inputKeyCode = kVK_ANSI_S;
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
    CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, inputKeyCode, YES);
    CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);
    CGEventRef saveCommandUp = CGEventCreateKeyboardEvent(source, inputKeyCode, NO);
    
    CGEventPost(kCGAnnotatedSessionEventTap, saveCommandDown);
    CGEventPost(kCGAnnotatedSessionEventTap, saveCommandUp);
    
    CFRelease(saveCommandUp);
    CFRelease(saveCommandDown);
    CFRelease(source);
    

    A CGKeyCode is nothing more than an unsigned integer:

    typedef uint16_t CGKeyCode;  //From CGRemoteOperation.h
    

    Your real issue will be turning a character (probably an NSString) into a keycode. Fortunately, the Shortcut Recorder project has code that will do just that in the SRKeyCodeTransformer.m file. It's great for transforming a string to a keycode and back again.

提交回复
热议问题