How to start and end an application from cocoa app on Mac

My Cocoa application must start and terminate other applications. Please let me know about any sample code that can do the following:

  • Launch the app from inside Cocoa code
  • End application from inside Cocoa code
+8
cocoa
source share
3 answers

As mentioned earlier, it is quite simple to launch other applications using the NSWorkspace class, for example:

- (BOOL)launchApplicationWithPath:(NSString *)path { // As recommended for OS X >= 10.6. if ([[NSWorkspace sharedWorkspace] respondsToSelector:@selector(launchApplicationAtURL:options:configuration:error:)]) return nil != [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:path isDirectory:NO] options:NSWorkspaceLaunchDefault configuration:nil error:NULL]; // For older systems. return [[NSWorkspace sharedWorkspace] launchApplication:path]; } 

You need to do a little more work to exit another application, especially if the goal is before 10.6, but it is not so difficult. Here is an example:

 - (BOOL)terminateApplicationWithBundleID:(NSString *)bundleID { // For OS X >= 10.6 NSWorkspace has the nifty runningApplications-method. if ([[NSWorkspace sharedWorkspace] respondsToSelector:@selector(runningApplications)]) for (NSRunningApplication *app in [[NSWorkspace sharedWorkspace] runningApplications]) if ([bundleID isEqualToString:[app bundleIdentifier]]) return [app terminate]; // If that didn't work then try using the apple event method, also works for OS X < 10.6. AppleEvent event = {typeNull, nil}; const char *bundleIDString = [bundleID UTF8String]; OSStatus result = AEBuildAppleEvent(kCoreEventClass, kAEQuitApplication, typeApplicationBundleID, bundleIDString, strlen(bundleIDString), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, ""); if (result == noErr) { result = AESendMessage(&event, NULL, kAEAlwaysInteract|kAENoReply, kAEDefaultTimeout); AEDisposeDesc(&event); } return result == noErr; } 
+7
source share

Assuming this targets 10.6, you can use NSRunningApplication along with NSWorkspace . First, you must determine if the application is running using:

 [[NSWorkspace sharedWorkspace] runningApplications] 

If it is not running, you can start it using NSWorkspace , but I recommend a new call to launchApplicationAtURL:options:configuration:error: which will return NSRunningApplication , which you can use to terminate the application. See NSWorkspace for more details.

+3
source share

To launch the application:

 [[NSWorkspace sharedWorkspace] launchApplication:@"App"]; 

From http://forums.macnn.com/79/developer-center/134947/launch-another-application-from-cocoa/

To leave:

NSApplication has -terminate: method: [NSApp terminate: nil];

From How can I tell my Cocoa application to exit the application itself?

+2
source share

Source: https://habr.com/ru/post/650785/


All Articles