Cocoa:隐藏一个应用程序

时间:2009-06-12 22:32:51

标签: cocoa hide

是否可以使用cocoa隐藏一个特定的应用程序?

我知道您可以使用以下代码隐藏所有其他应用程序

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

但是,是否可以隐藏一个特定的应用程序,例如Safari?

3 个答案:

答案 0 :(得分:8)

如果您的目标是Mac OS 10.6+,则可以使用新的NSRunningApplication类:

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

答案 1 :(得分:6)

你可以用applescript做到:

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

或通过调用:

从cocoa中调用相同的applescript
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];

答案 2 :(得分:3)

或者,如果您想避免Apple脚本并使用捆绑标识符而不是应用程序名称,可以将其本地化为Mike指出:

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);
    }
}