Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Dock icon without closing window

Tags:

macos

cocoa

dock

I am creating an app in which I want to give the user the ability to show or hide the dock icon at run time. I have a preferences window with a checkbox, setting a user default value, which fires the following code using KVO:

if (!hideDockIcon) {
    TransformProcessType(&psn, kProcessTransformToForegroundApplication);
} else {
    TransformProcessType(&psn, kProcessTransformToUIElementApplication);
}

This works, but when hiding, the preferences window is closed directly (which makes sense as it is now a background app). However, I noticed that MS's SkyDrive client manages to hide the icon while keeping the Preferences window open. I have not been able to find out how one would do that, anybody has an idea?

I also tried using [NSApp setActivationPolicy: NSApplicationActivationPolicyRegular] and NSApplicationActivationPolicyAccessory/NSApplicationActivationPolicyProhibited but that doesn't work for me; Accessory doesn't hide the dock icon, Prohibited closes the window as well and seems to make [NSApp activateIgnoringOtherApps:YES] being ignored.

like image 569
sgvd Avatar asked Nov 14 '12 13:11

sgvd


2 Answers

I stumbled upon this thread where the following is suggested to prevent a window from being hidden:

[window setCanHide:NO];

This just covers hiding. If your window gets closed, you might try to use the window delegate? There's a call that let's you prevent the window from being closed

- (BOOL)windowShouldClose:(id)sender
like image 158
Michael Starke Avatar answered Nov 13 '22 21:11

Michael Starke


I solved this problem by not activating the app in the same run loop turn:

dispatch_async(dispatch_get_main_queue(), ^{
    [NSApp activateIgnoringOtherApps:YES];
});

Swift:

dispatch_async(dispatch_get_main_queue()) { 
    NSApp.activateIgnoringOtherApps(true)
}

I'm calling dispatch_async to schedule the block for execution in one of the next run loop turns a few nanoseconds later. This gives the process the chance to finish hiding itself.

like image 1
WetFish Avatar answered Nov 13 '22 21:11

WetFish