Search code examples
macoscocoafocusmenubar

How do I save the focus context and return to it in an OSX application?


I'm writing a menubar application that shows a window when a global hotkey is pressed. The application has no dock icon and no normal menu (just the statusItem).

Prior to activating the application, lets say I have a text box on a webpage in chrome focused. How can I refocus that text box when my application is dismissed.

If you're familiar with Text Expander, they do something similar.


Solution

  • I figured this out. You need an NSRunningApplication:

    @implementation AppDelegate { NSRunningApplication *_previousApplication; }

    Then store the previous application before you become active:

    _previousApplication = [[NSWorkspace sharedWorkspace] frontmostApplication];

    Finally, after you deactivate, just bring back the other application:

    [_previousApplication activateWithOptions:NSApplicationActivateIgnoringOtherApps];