2011-01-07 63 views

回答

3

假设这是针对10.6,您可以使用NSRunningApplicationNSWorkspace一起。首先,你应该确定应用程序使用已经运行:

[[NSWorkspace sharedWorkspace] runningApplications] 

如果它没有运行,那么你可以使用NSWorkspace启动它,但我建议较新的呼叫,launchApplicationAtURL:options:configuration:error:,它会返回一个NSRunningApplication,你可以用来终止应用程序。有关更多详细信息,请参阅NSWorkspace

7

正如前面提到的它很容易启动其他应用程序与NSWorkspace类的帮助,例如:

- (BOOL)launchApplicationWithPath:(NSString *)path 
{ 
    // As recommended for OS X >= 10.6. 
    if ([[NSWorkspace sharedWorkspace] respondsToSelector:@selector(launchApplicationAtURL:options:configuration:error:)]) 
     return nil != [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:path isDirectory:NO] options:NSWorkspaceLaunchDefault configuration:nil error:NULL]; 

    // For older systems. 
    return [[NSWorkspace sharedWorkspace] launchApplication:path]; 
} 

你必须做更多的工作,以退出其他应用程序,尤其是如果目标是在10.6之前,但不是太难。这里是一个例子:

- (BOOL)terminateApplicationWithBundleID:(NSString *)bundleID 
{ 
    // For OS X >= 10.6 NSWorkspace has the nifty runningApplications-method. 
    if ([[NSWorkspace sharedWorkspace] respondsToSelector:@selector(runningApplications)]) 
     for (NSRunningApplication *app in [[NSWorkspace sharedWorkspace] runningApplications]) 
      if ([bundleID isEqualToString:[app bundleIdentifier]]) 
       return [app terminate]; 

    // If that didn‘t work then try using the apple event method, also works for OS X < 10.6. 

    AppleEvent event = {typeNull, nil}; 
    const char *bundleIDString = [bundleID UTF8String]; 

    OSStatus result = AEBuildAppleEvent(kCoreEventClass, kAEQuitApplication, typeApplicationBundleID, bundleIDString, strlen(bundleIDString), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, ""); 

    if (result == noErr) { 
     result = AESendMessage(&event, NULL, kAEAlwaysInteract|kAENoReply, kAEDefaultTimeout); 
     AEDisposeDesc(&event); 
    } 
    return result == noErr; 
}