【问题标题】:Quitting other applications in cocoa退出可可中的其他应用程序
【发布时间】:2013-02-27 04:57:47
【问题描述】:

我需要退出 cocoa 中的其他应用程序。我有一个来自通知的 userInfo 字典,告诉我应用程序的名称。我尝试了终止和强制终止的方法,但它们不起作用(我认为它们仅在雪豹中可用。)

【问题讨论】:

  • 如果你没有300分,你怎么能做赏金呢?
  • @boyfarrell - 我把赏金放在上面了。

标签: cocoa


【解决方案1】:

我们使用-[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);
}

【讨论】:

  • 可以预见,如果应用是沙盒化的,这似乎不起作用
【解决方案2】:

最佳解决方案(考虑到 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

Terminating Another App Running - Cocoa

【讨论】:

  • 这很好,但不适用于所有应用程序,所以我投了赞成票,但没有奖励赏金。
【解决方案3】:

您可以向应用程序发送退出 AppleEvent,请求应用程序退出,但我认为您不能在没有提升权限的情况下强制应用程序退出。查看Scripting Bridge 框架,了解发送所需事件的最可可方式。

【讨论】:

    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多