问题
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
回答1:
If you're running on Mac OS X 10.6, Snow Leopard, you can use the new NSRunningApplication terminate method.
回答2:
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, ¤tProcessPSN,
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.
回答3:
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.
来源:https://stackoverflow.com/questions/1469534/terminating-another-app-running-cocoa