Switching Between Dock and Status Bar Mode in Cocoa

Oct 16, 2012   #cocoa  #objective-c  #os x 

In this blog post I’ll show you how to make a Cocoa app that can switch between dock icon and statusbar icon mode.

For the basics on how to create a statusbar app see Cocoa Tips and Tricks.

I’ve tried several approaches to this topic but any other than the one I describe here had minor to major glitches such as not activating windows correctly when in statusbar mode for example.

In order to work fine, your application has to be a statusbar app by default. You achieve this by adding the key LSUIElement with a value of YES to your <Application>-Info.plist.

Now, when your application launches, check whether you want to display the statusbar icon or the dock icon. I do this based on the user’s preference in this example.

- (void)applicationDidFinishLaunching:(NSNotification *)notification { if(![[NSUserDefaults standardUserDefaults] boolForKey:@"showDockIcon"]) { // Create a status item and display it in the statusbar self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; [self.statusItem setMenu:self.statusBarMenu]; [self.statusItem setHighlightMode:YES]; [self.statusItem setImage:[NSImage imageNamed:@"barimage"]]; [self.statusItem setAlternateImage:[NSImage imageNamed:@"barimage-highlighted"]]; } else { // Bring the dock icon to the front (initially hidden with LSUIElement = YES in -Info.plist) ProcessSerialNumber psn = { 0, kCurrentProcess }; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } }