简体   繁体   中英

Terminating Another App Running - Cocoa

How can I terminate another app that is running in cooca. Let's say I have iTunes running, and I type in quit in my app, it would quit itunes. "iTunes" is just an example, it could be anything the user wants. 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. SIGTERM is a pretty brute-force, low-level way.

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:

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.

如果您在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. "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 -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. You could even go so far as Scripting Bridge , but for terminating an app, that would be overkill.

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"). For lower-level processes like daemons, you need other techniques like launchctl or kill , but we can talk about those if you need them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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