title: Generate keyboard events for the frontmost application
body: <p>In Mac OS / Cocoa, may I <strong>synthesize keyboard entries</strong> - strings - for the frontmost application in a transparent way?</p>
  
  <p>To be more precise, I don't want to send special characters or control sequences. My only need is to <strong>send standard characters</strong>.</p>
  
  <p>Just learned <a href="http://forums.macrumors.com/showthread.php?t=436511" rel="nofollow noreferrer">here</a>, that AppleScript can do the trick like this:</p>
  
  <pre><code>tell application "TextEdit"
      activate
  
      tell application "System Events"
          keystroke "f" using {command down}
      end tell
  end tell
  </code></pre>
  
  <p><strong>Q: How would I do this using ObjC / cocoa?</strong></p>
  
  <p><strong>UPDATE 2012-02-18 - Nicks proposal enhanced</strong></p>
  
  <p>Based on <a href="https://stackoverflow.com/users/9137/nick">Nick</a>'s code below, here is the final solution:</p>
  
  <pre><code>// First, get the PSN of the currently front app
  ProcessSerialNumber psn;
  GetFrontProcess( &amp;psn );
  
  // make some key events
  CGEventRef keyup, keydown;
  keydown = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)6, true);
  keyup = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)6, false);
  
  // forward them to the frontmost app
  CGEventPostToPSN (&amp;psn, keydown); 
  CGEventPostToPSN (&amp;psn, keyup); 
  
  // and finally behave friendly
  CFRelease(keydown);
  CFRelease(keyup);
  </code></pre>
  
  <p>Using this method, a click on a button of a non-activating panel targets the event to the actual front application. Perfectly what I want to do.</p>