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

时间:2011-01-07 02:19:35

标签: cocoa

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

  1. 从Cocoa代码
  2. 中启动一个应用程序
  3. 从Cocoa代码
  4. 中终止应用程序

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:3)

假设这是针对10.6的,您可以使用NSRunningApplicationNSWorkspace。首先,您应该使用以下命令确定应用程序是否已在运行:

[[NSWorkspace sharedWorkspace] runningApplications]

如果它没有运行,那么您可以使用NSWorkspace启动它,但我建议使用较新的调用launchApplicationAtURL:options:configuration:error:,它将返回NSRunningApplication,您可以使用它来终止应用。有关详细信息,请参阅NSWorkspace

答案 2 :(得分:2)

启动应用:

[[NSWorkspace sharedWorkspace] launchApplication:@"App"];

来自http://forums.macnn.com/79/developer-center/134947/launch-another-application-from-cocoa/

退出:

NSApplication有一个-terminate:方法:[NSApp terminate: nil];

来自How can I tell my Cocoa application to quit from within the application itself?