3

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.

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
Tony
  • 36,591
  • 10
  • 48
  • 83

1 Answers1

0

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.

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
  • the method is fine, but now in 2015 Apples CDO (Chief deprecation officer) has finally managed to deprecate `GetCurrentProcess` and `ProcessInformationCopyDictionary` and `GetProcessInformation`. He says we should use `NSRunningApplication` instead. Do you have any idea how this could possibly work? – Michael Jan 26 '15 at 13:26
  • Scanning the docs quickly, you could try `[[NSRunningApplication runningApplicationWithProcessIdentifier:getppid()] bundleIdentifier]`. – paulmelnikow Jan 26 '15 at 14:48
  • no sorry, this does not work. That expression always evaluated to `nil` in the cases I tested: start as login item; start from Xcode; start through Finder. Each I tested at two places with the same result: in main(), and after -applicationDidFinishLaunching: – Michael Jan 27 '15 at 09:18