Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register .Net Core Console App on MacOS in Login Items Programmatically

I have developed a console application in .net core which will be distributed to clients using Windows and MacOS. One of the requirements is that the console app should start up automatically once the device boots up. I am aware that this can be achieved on MacOS by adding the executable file in System Preferences --> Users & Groups --> Login Items.

I was wondering if this can be achieved by doing this programmatically in the Main method of the console application? In windows I can register the exe file in the windows registry to achieve this:

RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("My App Name", "/path/to/my/app/MyApp.exe");

Is this possible on MacOS or should this be a manual process invoked by the clients?

like image 955
Ruan Avatar asked Jun 08 '26 06:06

Ruan


1 Answers

Found the Solution. You need to make use of Apple Script commands:

public void SetAsStartupApp()
{
    var applicationName = "YourAppName";
    var applicationPath = "/Applications/YourAppName.app";

    var deleteError = new NSDictionary();
    var createError = new NSDictionary();

    // Prevent Duplicate entry in Login items
    var deleteScript = new NSAppleScript($"tell application \"System Events\" \n if exists login item \"{applicationName}\" then \n delete login item \"{applicationName}\" \n end if \n end tell");
    deleteScript.ExecuteAndReturnError(out deleteError);

    // Create entry in Login Items
    var createScript = new NSAppleScript($"tell application \"System Events\" to make login item at end with properties {{path:\"{applicationPath }\", hidden:false}}");
    createScript.ExecuteAndReturnError(out createError);

    // Handle Errors...
}
like image 199
Ruan Avatar answered Jun 10 '26 17:06

Ruan