Simulate keypress for system wide hotkeys

后端 未结 4 391
旧巷少年郎
旧巷少年郎 2020-12-02 19:31

I need to simulate keystrokes in OSX. Here\'s how I do it:

-(void)execute {
    CGEventSourceRef sourceRef =
    CGEventSourceCreate(kCGEventSourceStateHIDSy         


        
4条回答
  •  青春惊慌失措
    2020-12-02 20:15

    From the documentation for CGEventCreateKeyboardEvent:

    All keystrokes needed to generate a character must be entered, including modifier keys. For example, to produce a 'Z', the SHIFT key must be down, the 'z' key must go down, and then the SHIFT and 'z' key must be released:

    So, you can't just press and release space with the option modifier to trigger an option-space; you have to press option, press space, release space, release option.

    As a side note, opt-space doesn't do anything by default; cmd-space is the Spotlight search hotkey, and cmd-opt-space is the Spotlight window hotkey.

    So, this code will pop up the Spotlight search:

    - (void)execute {
      CGEventSourceRef src = 
        CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
    
      CGEventRef cmdd = CGEventCreateKeyboardEvent(src, 0x38, true);
      CGEventRef cmdu = CGEventCreateKeyboardEvent(src, 0x38, false);
      CGEventRef spcd = CGEventCreateKeyboardEvent(src, 0x31, true);
      CGEventRef spcu = CGEventCreateKeyboardEvent(src, 0x31, false);
    
      CGEventSetFlags(spcd, kCGEventFlagMaskCommand);
      CGEventSetFlags(spcu, kCGEventFlagMaskCommand);
    
      CGEventTapLocation loc = kCGHIDEventTap; // kCGSessionEventTap also works
      CGEventPost(loc, cmdd);
      CGEventPost(loc, spcd);
      CGEventPost(loc, spcu);
      CGEventPost(loc, cmdu);
    
      CFRelease(cmdd);
      CFRelease(cmdu);
      CFRelease(spcd);
      CFRelease(spcu);
      CFRelease(src);  
    }
    

提交回复
热议问题