title: Cocoa put window in the foreground
body: <p>I am building a Cocoa Mac application that runs in the background but has a main window.</p>
  
  <p>To make it run in the background I've set "Application is background only" to "YES".</p>
  
  <p>I built a system tray:</p>
  
  <p><img src="https://i.stack.imgur.com/srqLG.png" alt="system tray"></p>
  
  <p>If you close the main window, you can re-open it by clicking "open".</p>
  
  <p>I have however some issues with the layering of windows:</p>
  
  <ul>
  <li>When I start the application, the main window opens however it appears in the background, behind any other windows or applications I have open at the time.</li>
  <li>Clicking on "open" doesn't bring the window to the foreground. It opens it correctly if it was closed, however it stays behind any windows.</li>
  <li>Clicking on preferences or about has the same issue. It opens the correct window but it appears behind any other windows.</li>
  <li>On my main window there is a textfield. I can click on it, the cursor blinks as if I am ready to type. But when I type it actually types in some other background window! For example if I have TextWrangler open in the background, it will type there instead of the textfield...</li>
  </ul>
  
  <p>Here is my code for handling the "open":</p>
  
  <pre><code>- (IBAction)show:(id)sender {
      [NSApp activateIgnoringOtherApps:YES];
      [window makeKeyAndOrderFront:sender];   
  }
  </code></pre>
  
  <p>Note that IF I set "Application is background only" to "NO" (which means I have a dock icon appearing), then clicking on "open" brings the window to the foreground as expected. And typing in the textfield works as expected.</p>