Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quitting other applications in cocoa

Tags:

cocoa

I need to quit other applications in cocoa. I have a userInfo dictionary from a notification that tells me the name of the application. I tried the methods terminate and forceTerminate, but they did not work (I think they are only available in snow leopard.)

like image 580
user657819 Avatar asked Mar 13 '11 19:03

user657819


3 Answers

We use -[NSWorkspace runningApplications]. It requires 10.6 or higher.

void SendQuitToProcess(NSString* named)
{   

    for ( id app in [[NSWorkspace sharedWorkspace] runningApplications] ) 
    {
        if ( [named isEqualToString:[[app executableURL] lastPathComponent]]) 
        {
            [app terminate];
        }
    }

}

otherwise, you'll have to use AppleScript. You can do something corny like this:

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);
}
like image 105
Ken Aspeslagh Avatar answered Oct 15 '22 04:10

Ken Aspeslagh


The best solution (accounting for all the different API's available in the last 3-4 versions of OS X) is going to be using AppleScript. Just generate the necessary script in Obj-C/Python/Java whatever it is you are actually using (I'm assuming Obj-C since you specifically said 'In Cocoa'). And execute it using the NSAppleScript class (a contrived example):

// 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);

This effectively runs a script that (if appName was 'Safari') looks like:

tell application "Safari"
quit
end tell

That or check out this SO question

Terminating Another App Running - Cocoa

like image 30
G. Shearer Avatar answered Oct 15 '22 04:10

G. Shearer


You can send the application a quit AppleEvent, requesting the application quit, but I don't think you can force an application to quit without elevated privileges. Take a look at the Scripting Bridge framework for the most Cocoa-y way to send the required events.

like image 23
Barry Wark Avatar answered Oct 15 '22 04:10

Barry Wark