Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell whether a Mac Cocoa application has been launched normally or as a login item?

Tags:

macos

cocoa

Is there any way of telling whether a Cocoa application has been launched as a log item rather than by double clicking it?

like image 316
Frank R. Avatar asked Apr 06 '11 08:04

Frank R.


2 Answers

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
like image 166
Ken Thomases Avatar answered Sep 29 '22 14:09

Ken Thomases


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 :)

like image 30
Anne Avatar answered Sep 29 '22 13:09

Anne