Is there a way to distinguish app being started by Launch Services at login or by user?

527 Views Asked by At

Cocoa app can add themselves to LSSharedFileList's list of login items. This will allow application to be started when user logs in. However, is there a way to tell whether user started the application or the app auto-started at login? This is useful because in one case we can show a user interface in another we can hide the UI and run the app in background as a menubar app.

1

There are 1 best solutions below

3
On

Here's some code for this. I'm not sure what it returns for login items, but if you try it out and comment I'll update the post. It does return com.apple.Finder for Finder and com.apple.dt.Xcode for Xcode.

+ (NSString *) bundleIdentifierOfParentProcess {
    NSString *result = nil;
    ProcessSerialNumber psn = {0, 0};
    if (0 == GetCurrentProcess(&psn)) {
        ProcessInfoRec myProcessInfo;
        myProcessInfo.processInfoLength = sizeof(ProcessInfoRec);
        myProcessInfo.processName = NULL;
        myProcessInfo.processAppRef = NULL;
        if (0 == GetProcessInformation(&psn, &myProcessInfo)) {
            ProcessSerialNumber parentPSN = myProcessInfo.processLauncher;
            CFDictionaryRef parentProcessInfo =
            ProcessInformationCopyDictionary(&parentPSN,
                                             kProcessDictionaryIncludeAllInformationMask);
            if (parentProcessInfo) {
                result =
                [(__bridge NSDictionary *) parentProcessInfo objectForKey:
                (__bridge id) kCFBundleIdentifierKey];
                CFRelease(parentProcessInfo);
            }
        }
    }
    return result;
}

parentProcessInfo is a dictionary full of values which may also be helpful, in case the bundle identifier isn't meaningful enough.