How to get other application to paste from my global hotkey

三世轮回 提交于 2019-12-02 09:57:24

You don't want to use a global hot key for this. You want to write your application so that it provides a "service". See the Services Implementation Guide.

Your service can be activated by a keyboard shortcut, either the default configured in your app's Info.plist or one configured by the user in System Preferences.

Cocoa takes care of both copying from the active app and pasting into it after you've done the transformation, so this will take care of the first and third steps.

Services use a separate pasteboard for transferring data, so this also doesn't interfere with the contents of the general (copy and paste) pasteboard.

It's a superior approach on every level.


Edited to add other benefits:

A service won't steal a keyboard shortcut from the active app.

A service is also available via the application menu and context menu. That makes it discoverable.

It turns out there is a way to do what I want.

void pasteCurrent() {

    CGEventRef commandDown = CGEventCreateKeyboardEvent(NULL, kVK_Command, YES);
    CGEventRef VDown = CGEventCreateKeyboardEvent(NULL, kVK_ANSI_V, YES);

    CGEventRef VUp = CGEventCreateKeyboardEvent(NULL, kVK_ANSI_V, NO);
    CGEventRef commandUp = CGEventCreateKeyboardEvent(NULL, kVK_Command, NO);

    CGEventSetFlags(VDown,kCGEventFlagMaskCommand);
    CGEventSetFlags(VUp,kCGEventFlagMaskCommand);

    CGEventPost(kCGHIDEventTap, commandDown);
    CGEventPost(kCGHIDEventTap, VDown);
    CGEventPost(kCGHIDEventTap, VUp);
    CGEventPost(kCGHIDEventTap, commandUp);

    CFRelease(commandDown);
    CFRelease(VDown);
    CFRelease(VUp);
    CFRelease(commandUp);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!