How to launch application and bring it to front using Cocoa api?

后端 未结 7 1062
滥情空心
滥情空心 2020-11-29 07:27

I\'m very new to a cocoa programming and I can\'t find the way to do the following:

  • Start a particular application by name
  • Do some work
  • Later
相关标签:
7条回答
  • 2020-11-29 08:06

    To launch an application :

    [[NSWorkspace sharedWorkspace] launchApplication:@"/Applications/Safari.app"];
    

    To activate an app :

    NSRunningApplication* app = [NSRunningApplication
                                 runningApplicationWithProcessIdentifier: PID];
    [app activateWithOptions: NSApplicationActivateAllWindows];
    // or
    NSArray* apps = [NSRunningApplication
                     runningApplicationsWithBundleIdentifier:@"com.bla.blah"];
    [(NSRunningApplication*)[apps objectAtIndex:0]
     activateWithOptions: NSApplicationActivateAllWindows];
    
    0 讨论(0)
  • 2020-11-29 08:07

    NSRunningApplication is available on Mac OS X 10.6 or later.

    If you have to support earlier systems, this can be done with APIs such as GetCurrentProcess() and SetFrontProcess() and the old ProcessSerialNumber structure.

    0 讨论(0)
  • 2020-11-29 08:11

    Did you look into NSRunningApplication?

    0 讨论(0)
  • 2020-11-29 08:13

    To start an application, use the NSWorkspace class: NSWorkspace Reference

    Specifically, the launchApplication: function.

    I don't know the answer of the activation part off my head. You can activate your own application with -[NSApplication activateIgnoringOtherApps:], but I don't know how to do it for other apps.

    0 讨论(0)
  • 2020-11-29 08:18

    In swift 4, you can use NSWorkspace.shared.launchApplication(appName:) to open an app. It also makes the launched app at front in my case.

    You also can try:

    do {
        try NSWorkspace.shared.launchApplication(at: yourAppURL,
                                                 options: .andHideOthers,
                                                 configuration: [:])
    } catch {
        printError("Failed to launch the app.")
    }
    

    Option andHideOthers: Hide all apps except the newly launched one.

    0 讨论(0)
  • 2020-11-29 08:22

    Open App in Mac in Objective C

    #import <Cocoa/Cocoa.h>
    
    int main(int argc, const char * argv[]) {
    
        @autoreleasepool {
            // insert code here...
            [[NSWorkspace sharedWorkspace] launchApplication:@"/Applications/Books.app"];
        }
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题