Is there any way of telling whether a Cocoa application has been launched as a log item rather than by double clicking it?
When an application is launched without a document to open or print, it receives an 'oapp' (a.k.a. kAEOpenApplication) Apple Event. That event may have a property data (keyAEPropData) parameter. For an ordinary launch, that parameter is absent or 0. For a launch from a login item, it's keyAELaunchedAsLogInItem. (When your app is launched to provide a service, it's keyAELaunchedAsServiceItem.)
https://developer.apple.com/legacy/library/documentation/Carbon/Reference/Apple_Event_Manager/index.html#//apple_ref/doc/constant_group/Launch_Apple_Event_Constants
You can check for this with the following code in your -applicationWill/DidFinishLaunching: method:
NSAppleEventDescriptor* event = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
if ([event eventID] == kAEOpenApplication &&
[[event paramDescriptorForKeyword:keyAEPropData] enumCodeValue] == keyAELaunchedAsLogInItem)
{
// you were launched as a login item
}
Swift 3:
let event = NSAppleEventManager.shared().currentAppleEvent
let launchedAsLogInItem =
event?.eventID == kAEOpenApplication &&
event?.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem
As far i'm aware there is no proper way to check this, but there are some thoughts:
Best solution:
Create two different applications, for example TheApp and TheAppLauncher.
Add TheApp to the applications folder and TheAppLaucher to the startup items.
Simply launch TheApp with a specific flag when TheAppLauncher is launched.
I hope this is clear :)
Other 'ugly' option:
Check whether the application is actually listed in the login items:
https://github.com/carpeaqua/Shared-File-List-Example/
Make the application log the exact time it launched.
Then compare it with the last time the user logged-in.
The finger command provides this information (use NSTask).
Good change it's launched as log-in item when the difference is small.
But yes, this is not completely reliable :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With