简体   繁体   English

终止另一个运行的应用程序 - 可可

[英]Terminating Another App Running - Cocoa

How can I terminate another app that is running in cooca. 如何终止在cooca中运行的另一个应用程序。 Let's say I have iTunes running, and I type in quit in my app, it would quit itunes. 假设我有iTunes运行,我在我的应用程序中键入退出,它将退出iTunes。 "iTunes" is just an example, it could be anything the user wants. “iTunes”只是一个例子,它可以是用户想要的任何东西。 I can open any app from my application, but I want to know how to close any app running. 我可以从我的应用程序中打开任何应用程序,但我想知道如何关闭任何运行的应用程序。

thanks 谢谢

kevin 凯文

AppleScript is a pretty high-level way to send a single Quit event. AppleScript是一种发送单个Quit事件的高级方法。 SIGTERM is a pretty brute-force, low-level way. SIGTERM是一种非常强大,低级的方式。

The correct way to quit another application is to obtain its Process Serial Number (psn) and send it a kAEQuitApplication Apple event with these two lines of code: 退出另一个应用程序的正确方法是获取其进程序列号(psn)并使用以下两行代码向其发送kAEQuitApplication Apple事件:

result = AEBuildAppleEvent( kCoreEventClass, kAEQuitApplication, typeProcessSerialNumber, &currentProcessPSN,
sizeof(ProcessSerialNumber), kAutoGenerateReturnID, kAnyTransactionID, &tAppleEvent, &tAEBuildError,"");
result = AESend( &tAppleEvent, &tReply, kAEAlwaysInteract+kAENoReply, kAENormalPriority, kNoTimeOut, nil, nil );        

You can do this from C, C++, or Objective-C, and you have to link with CoreServices.framework. 您可以从C,C ++或Objective-C执行此操作,并且必须与CoreServices.framework链接。

如果您在Mac OS X 10.6,Snow Leopard上运行,则可以使用新的NSRunningApplication终止方法。

For high-level applications like iTunes, based on Carbon or Cocoa, they're going to respond to Applescript. 对于像iTunes这样基于Carbon或Cocoa的高级应用程序,他们将对Applescript做出回应。 "Quit" is part of the standard package. “退出”是标准包的一部分。 You just need to send: 你只需要发送:

tell application "iTunes" to quit

There are lots of ways to do that. 有很多方法可以做到这一点。 The simplest to implement is to make a system call to osascript : 最简单的实现是对osascript进行系统调用:

osascript -e 'tell application "iTunes" to quit'

You can go up from there to more powerful tools like Apple Events , which would be very appropriate for this problem. 您可以从那里上升到更强大的工具,如Apple Events ,这非常适合这个问题。 You could even go so far as Scripting Bridge , but for terminating an app, that would be overkill. 你甚至可以使用Scripting Bridge ,但是为了终止应用程序,这将是一种过度杀伤力。

This will only work for programs that respond to Applescript, but that should be any program that you would see in your dock (and which I assume you mean by "applications"). 这只适用于响应Applescript的程序,但这应该是您在Dock中看到的任何程序(我认为您的意思是“应用程序”)。 For lower-level processes like daemons, you need other techniques like launchctl or kill , but we can talk about those if you need them. 对于像守护进程这样的低级进程,你需要其他技术,如launchctlkill ,但是如果你需要它们我们可以讨论它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM