如何在Mac上的cocoa应用程序内启动和终止应用程序

我的Cocoa应用程序需要启动和终止其他应用程序.请告诉我任何可以执行以下操作的示例代码:

>从Cocoa代码中启动一个应用程序
>从Cocoa代码中终止应用程序

最佳答案
如前所述,在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;
}

转载注明原文:如何在Mac上的cocoa应用程序内启动和终止应用程序 - 代码日志