Send a keyboard shortcut to a Mac OS X Window

后端 未结 2 1796
刺人心
刺人心 2020-12-25 09:51

Is it possible for one window on a Mac desktop to programatically send a keyboard shortcut or key sequence to another?

I\'m looking to control an application which o

2条回答
  •  长发绾君心
    2020-12-25 10:37

    You can do this without need for AppleScript also. Here's an example working code which sends a key code with modifiers.

    -Edit: this won't let you target a specific app, only post keystrokes to the whole system (as if pressed on a keyboard)

    #include 
    // you can find key codes in , for example kVK_ANSI_A is 'A' key
    // modifiers are flags such as kCGEventFlagMaskCommand
    
    void PostKeyWithModifiers(CGKeyCode key, CGEventFlags modifiers)
    {
            CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
    
            CGEventRef keyDown = CGEventCreateKeyboardEvent(source, key, TRUE);
            CGEventSetFlags(keyDown, modifiers);
            CGEventRef keyUp = CGEventCreateKeyboardEvent(source, key, FALSE);
    
            CGEventPost(kCGAnnotatedSessionEventTap, keyDown);
            CGEventPost(kCGAnnotatedSessionEventTap, keyUp);
    
            CFRelease(keyUp);
            CFRelease(keyDown);
            CFRelease(source);  
    }
    

提交回复
热议问题