title: Simulate keypress for system wide hotkeys
body: <p>I need to simulate keystrokes in OSX. Here's how I do it:</p>
  
  <pre><code>-(void)execute {
      CGEventSourceRef sourceRef =
      CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  
      CGEventRef keyPress = CGEventCreateKeyboardEvent (sourceRef, (CGKeyCode)keyCode, true);
      CGEventRef keyUnpress = CGEventCreateKeyboardEvent (sourceRef, (CGKeyCode)keyCode, false);
  
      CGEventSetFlags(keyPress, modifierFlags);
      CGEventPost(kCGHIDEventTap, keyPress);
  
      //unpressing the acualkey
      CGEventPost(kCGHIDEventTap, keyUnpress);
  
      CFRelease(keyPress);
      CFRelease(keyUnpress);
      CFRelease(sourceRef);
  }
  </code></pre>
  
  <p>It works fine for every hotkey or simple keystrokes in any app, but doesn't work for system wide shortcuts, for example <kbd>option + space</kbd> to launch Spotlight or <kbd>cmd + shift + 4</kbd> to make a screenshot or <kbd>ctrl + `</kbd> to open iTerm2 window.</p>
  
  <p>I tried to change event's source and the location at which to post event, doesn't help. Any ideas?</p>