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

巧了我就是萌 提交于 2020-01-13 13:45:23

问题


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:


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.



来源:https://stackoverflow.com/questions/15395202/is-there-a-way-to-distinguish-app-being-started-by-launch-services-at-login-or-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!