title: Send NSEvent to background app
body: <p>I need to send the key combo ^⌘C to a background app with the bundle identifier <code>com.company.app</code>. The key combo should then activate a menu item in that application.</p>
  
  <p>Unfortunately, I have no clue how to do that. Some research pointed me to the NSEvent and CGEvent API using <code>CGEventPostToPSN()</code>, but I was unable to get it work correctly, as I don't know how to set up the key combo. <code>CGEventPost()</code> didn't seem to work with the events I created, even if the desired app is the active one.</p>
  
  <p>Here is the code I eventually came up with but that doesn't work:</p>
  
  <pre><code>CGWindowID windowNumber;
  NSEvent *event = [NSEvent keyEventWithType:NSKeyUp
                                    location:NSZeroPoint
                               modifierFlags:(NSControlKeyMask | NSCommandKeyMask)
                                   timestamp:[[NSProcessInfo processInfo] systemUptime]
                                windowNumber:windowNumber
                                     context:[NSGraphicsContext currentContext]
                                  characters:@"c"
                 charactersIgnoringModifiers:@"c"
                                   isARepeat:NO
                                     keyCode:8];
  CGEventRef eventRef = [event CGEvent];
  </code></pre>
  
  <p>What am I supposed to do with that event now? Why is there no <code>NSEvent</code> equivalent for <code>CGEventPost()</code>? Is there even an easier way to activate that menu item than posting an event? I can easily get an instance of <code>NSRunningApplication</code>, but there is no suitable API to accomplish my task.</p>
  
  <p><strong>Update:</strong>
  I got it working:</p>
  
  <pre><code>- (void) postFakedKeyboardEventForCopyScreenToPasteboardToPSN:(ProcessSerialNumber)psn {
      CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);
      CGEventRef keyDownEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)8, true);
      CGEventSetFlags(keyDownEvent, (kCGEventFlagMaskControl | kCGEventFlagMaskCommand));
      CGEventRef keyUpEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)8, false);
      CGEventSetFlags(keyUpEvent, (kCGEventFlagMaskControl | kCGEventFlagMaskCommand));
      CFRelease(source);
  
      CGEventPostToPSN(&amp;psn, keyDownEvent);
      CFRelease(keyDownEvent);
      CGEventPostToPSN(&amp;psn, keyUpEvent);
      CFRelease(keyUpEvent);
  }
  </code></pre>
  
  <p>...</p>
  
  <pre><code>OSStatus err = noErr;
  ProcessSerialNumber psn;
  err = GetProcessForPID([simulator processIdentifier], &amp;psn);
  if (err == noErr)
      [self postFakedKeyboardEventForCopyScreenToPasteboardToPSN:psn];
  </code></pre>