Question

To remove the app icon in the Dock I use this code:

ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToUIElementApplication);

This code hides the icon in the Dock, but it also closes application window. It is possible to hide icon without closing main window?

[self.window setCanHide:NO];

This is not a solution, because when the user select Hide Others from another application menu app will not be hidden.

Was it helpful?

Solution

I'm not sure I understand what you mean in the last sentence "This is not a solution, because when the user select Hide other from another application menu app will not be hidden." But if you want the window to remain open when you go through the code

ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToUIElementApplication);

And you want it to hide itself at some other times, you could try using

[yourWindow setCanHide:NO];
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToUIElementApplication);

And once the code has run to hide the app icon, use [yourWindow setCanHide:YES];, so that the window is hidden during other processes. (This, for instance, might be useful to prevent a preferences window from hiding when you toggle a "Show App Icon" button, but still want the preferences window to hide when you interact with other windows of the app.

OTHER TIPS

The app's windows are not getting closed but just hidden because the app gets hidden.

A cleaner solution to hiding the app icon without hiding the windows is this, which unhides the app afterwards. And to prevent flicker due to hiding, then unhiding, the window(s), it temporarily also disables their hiding:

// Disable our windows from getting hidden
NSMutableArray<NSWindow*> *windowsThatCanHide = [NSMutableArray array];
for (NSWindow *w in NSApp.windows.copy) {
    if (w.canHide) {
        [windowsThatCanHide addObject:w];
        w.canHide = NO;
    }
}

// Remove icon from Dock (Note: This also inevitably hides the menu bar!)
TransformProcessType(&psn, kProcessTransformToUIElementApplication);

// Re-activate this app and re-enable the hiding of windows.
dispatch_async(dispatch_get_main_queue(), ^{
    for (NSWindow *w in windowsThatCanHide) {
        w.canHide = YES;
    }
    [NSApp unhide:self];
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top