【发布时间】:2013-02-27 04:57:47
【问题描述】:
我需要退出 cocoa 中的其他应用程序。我有一个来自通知的 userInfo 字典,告诉我应用程序的名称。我尝试了终止和强制终止的方法,但它们不起作用(我认为它们仅在雪豹中可用。)
【问题讨论】:
-
如果你没有300分,你怎么能做赏金呢?
-
@boyfarrell - 我把赏金放在上面了。
标签: cocoa
我需要退出 cocoa 中的其他应用程序。我有一个来自通知的 userInfo 字典,告诉我应用程序的名称。我尝试了终止和强制终止的方法,但它们不起作用(我认为它们仅在雪豹中可用。)
【问题讨论】:
标签: cocoa
我们使用-[NSWorkspace runningApplications]。它需要 10.6 或更高版本。
void SendQuitToProcess(NSString* named)
{
for ( id app in [[NSWorkspace sharedWorkspace] runningApplications] )
{
if ( [named isEqualToString:[[app executableURL] lastPathComponent]])
{
[app terminate];
}
}
}
否则,您将不得不使用 AppleScript。你可以做一些老生常谈的事情:
void AESendQuitToProcess(const char* named)
{
char temp[1024];
sprintf(temp, "osascript -e \"tell application \\\"%s\\\"\" -e \"activate\" -e \"quit\" -e \"end tell\"", named);
system(temp);
}
【讨论】:
最佳解决方案(考虑到 OS X 的最后 3-4 个版本中可用的所有不同 API)将使用 AppleScript。只需在 Obj-C/Python/Java 中生成必要的脚本,无论您实际使用的是什么(我假设是 Obj-C,因为您特别说过“在 Cocoa 中”)。并使用 NSAppleScript 类执行它(一个人为的例子):
// Grab the appName
NSString *appName = [someDict valueForKey:@"keyForApplicationName"];
// Generate the script
NSString *appleScriptString =
[NSString stringWithFormat:@"tell application \"%@\"\nquit\nend tell",
appName];
// Execute the script
NSDictionary *errorInfo = nil;
NSAppleScript *run = [[NSAppleScript alloc] initWithSource:theScript];
NSAppleEventDescriptor *theDescriptor = [run executeAndReturnError:&errorInfo];
// Get the result if your script happens to return anything (this example
// really doesn't return anything)
NSString *theResult = [theDescriptor stringValue];
NSLog(@"%@",theResult);
这有效地运行了一个脚本(如果 appName 是 'Safari')看起来像:
tell application "Safari"
quit
end tell
那个或者看看这个 SO question
【讨论】:
您可以向应用程序发送退出 AppleEvent,请求应用程序退出,但我认为您不能在没有提升权限的情况下强制应用程序退出。查看Scripting Bridge 框架,了解发送所需事件的最可可方式。
【讨论】: