2011-01-07 59 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; 
}