Simulating key press events in Mac OS X

后端 未结 2 1900
心在旅途
心在旅途 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.

    0 讨论(0)
  • 2020-11-29 05:22

    Just in case some one needs a Swift version:

    XCode 7.3 and Swift 2.2:

    let event1 = CGEventCreateKeyboardEvent(nil, 0x09, true); // cmd-v down
    CGEventSetFlags(event1, CGEventFlags.MaskCommand);
    CGEventPost(CGEventTapLocation.CGHIDEventTap, event1);
    
    let event2 = CGEventCreateKeyboardEvent(nil, 0x09, false); // cmd-v up
    CGEventSetFlags(event2, CGEventFlags.MaskCommand);
    CGEventPost(CGEventTapLocation.CGHIDEventTap, event2);
    

    Code above simulates CMD-V pressed then released(AKA: paste).

    0 讨论(0)
提交回复
热议问题