gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:06:19 30 4
gpt4 key购买 nike

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

  1. 从 Cocoa 代码内部启动应用程序
  2. 从 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;
}

关于cocoa - 如何从 Mac 上的 cocoa 应用程序内部启动和终止应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4621974/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com