How to paste text from one app to another using Cocoa?

后端 未结 3 456

I have read about NSPasteBoard in the Apple documentation, and how it allows for applications to write into the PasteBoard and allow other applicat

3条回答
  •  情深已故
    2020-12-31 20:02

    Here's some working code to post the ⌘+key event (assuming a known keycode):

    // some common keycodes
    #define KEY_CODE_x ((CGKeyCode)7)
    #define KEY_CODE_c ((CGKeyCode)8)
    #define KEY_CODE_v ((CGKeyCode)9)
    
    void DCPostCommandAndKey(CGKeyCode key)
    {
        CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
    
        CGEventRef keyDown = CGEventCreateKeyboardEvent(source, key, TRUE);
        CGEventSetFlags(keyDown, kCGEventFlagMaskCommand);
        CGEventRef keyUp = CGEventCreateKeyboardEvent(source, key, FALSE);
    
        CGEventPost(kCGAnnotatedSessionEventTap, keyDown);
        CGEventPost(kCGAnnotatedSessionEventTap, keyUp);
    
        CFRelease(keyUp);
        CFRelease(keyDown);
        CFRelease(source);  
    }
    

提交回复
热议问题