tags:

views:

142

answers:

3

How do I programmatically set an application bundle on Mac OS X to run when the user logs in?

Basically, the equivalent of the HKCU\Software\Microsoft\Windows\CurrentVersion\Run registry key in Windows.

+4  A: 

You can add the application to the user's "Login Items" (under System Preferences=>Accounts=[user]) or you can add a launchd agent to the user's ~/Library/LaunchAgents folder (see man launchd.plist). Use ~/Library/LaunchDaemons/ if your app has no user-facing UI. As others point out, launchd gives you a lot of control over when the app starts, what happens if the app quits or crashes, etc. and is most appropriate for "daemon" style apps (with our without UI).

The first option (Login Items) can be manipulated programmatically (link from Gordon).

Barry Wark
Could you perhaps elaborate on how I could do this with AppleScript? (or C++)
Jake Petroules
Apple's [dev docs on the subject](http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html) describe 3 methods for adding a Login Item, with a code snippet for one and a link to sample code for another.
Gordon Davisson
+3  A: 

The "correct" method is to create a LaunchAgent for processes you want to start at login that may have a UI and a LaunchDaemon for those that should be pure background processes. In your installer drop your plist into the correct folder, either for the user, or all users, or the system. The reason this method is superior is because you can use launchd to control how your process is run including the built-in ability to make sure it keeps running even if it crashes or is killed by the user.

Jeremy
This isn't a critical application that *must* be kept running, it's just for a convenience option in the preferences dialog. Are you saying it'll keep running the application if users exit it? I don't want that to happen.
Jake Petroules
No, I'm saying that's an option when you use LaunchDaemons. You can choose how you want the system to run your application.
Jeremy
A: 

Wanted to throw this out here for anyone using Qt / C++. Qt makes it super easy to use plists through the QSettings class. Check out this code snippet from a sample dummy application.

void MainWindow::readPlist()
{
    QSettings settings(appPlistPath, QSettings::NativeFormat);
    QVariant value = settings.value("mykey");
    QMessageBox::information(this, "Your Value", value.toString());
}

void MainWindow::addPlistEntry()
{
    QSettings settings(appPlistPath, QSettings::NativeFormat);
    settings.setValue("mykey", "myvalue");
}

void MainWindow::removePlistEntry()
{
    QSettings settings(appPlistPath, QSettings::NativeFormat);
    settings.remove("mykey");
}
jocull