views:

367

answers:

3

Is it possible to hide one specific application using cocoa?

I know you can hide all other applications using the following code

[[NSWorkspace sharedWorkspace] performSelectorOnMainThread:@selector(hideOtherApplications) withObject:NULL waitUntilDone:NO];

But is it possible to hide just one specific application say Safari for example?

+5  A: 

you can do it with applescript:

tell application "System Events" to set visible of process "Safari" to false

or call the same applescript from within cocoa by calling:

NSString * source = @"tell application \"System Events\" to set visible of process \"Safari\" to false";
NSAppleScript * script = [[NSAppleScript alloc] initWithSource:source];
[script executeAndReturnError:nil];
[script release];
cobbal
Thank you, works perfectly
Note that while this is probably fine for Safari, you would not want to hardcode it for some other apps as their process name may be localized to match the user's preferences
Mike Abdullah
+3  A: 

Or if you want to avoid Apple Script and use the bundle identifier instead of the application name which could be localized as Mike pointed:

for (NSDictionary *app in [[NSWorkspace sharedWorkspace] launchedApplications])
{
    if ([@"com.apple.Safari" isEqualToString:[app objectForKey:@"NSApplicationBundleIdentifier"]])
    {
        ProcessSerialNumber psn;
        GetCurrentProcess(&psn); // Initialize the Process Manager
        psn.highLongOfPSN = [[app objectForKey:@"NSApplicationProcessSerialNumberHigh"] intValue];
        psn.lowLongOfPSN = [[app objectForKey:@"NSApplicationProcessSerialNumberLow"] intValue];
        ShowHideProcess(&psn, NO);
    }
}
0xced
+2  A: 

If you are targeting Mac OS 10.6+, you can use the new NSRunningApplication class:

- (BOOL) hideAppWithBundleID:(NSString *)bundleID
{
    NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID];
    if ([apps count] == 0)
        return NO;
    return [(NSRunningApplication *)[apps objectAtIndex:0] hide];
}
hasseg