Search code examples
xamarinauthenticationstartupxamarin.mac

Xamarin MacOS app launch at login


I'm trying to make my Xamarin MacOS App to run at login. Looking around I found only very old topics with no solutions.

Is there any solution available? Is feasible?

My App runs, by default with Administrator Privileges

Thanks


Solution

  • I wrote this article some time ago. It should still be valid https://shamsutdinov.net/2016/09/27/how-to-launch-at-login-your-xamarin-mac-sandboxed-application/

    tl;dr;

    Your app should run in the sandbox: sandboxed app In your main app add this code

    public class StartAtLoginOption
    {
        [DllImport("/System/Library/Frameworks/ServiceManagement.framework/ServiceManagement")]
        static extern bool SMLoginItemSetEnabled(IntPtr aId, bool aEnabled);
    
    
        public static bool StartAtLogin(bool value)
        {
            CoreFoundation.CFString id = new CoreFoundation.CFString("my.helper.app.bundle.id");
            return SMLoginItemSetEnabled(id.Handle, value);
        }
    }
    

    Create a helper app which only runs in background: backgroung app

    Start your main app from the helper app:

    public override void DidFinishLaunching(NSNotification notification)
    {
        if (!NSWorkspace.SharedWorkspace.RunningApplications.Any(a => a.BundleIdentifier == "my.main.app.bundle.id"))
        {
            var path = new NSString(NSBundle.MainBundle.BundlePath)
                .DeleteLastPathComponent()
                .DeleteLastPathComponent()
                .DeleteLastPathComponent()
                .DeleteLastPathComponent();
            var pathToExecutable = path + @"Contents/MacOS/LoginItemTestMain";
    
            if (NSWorkspace.SharedWorkspace.LaunchApplication(pathToExecutable)) { }
            else NSWorkspace.SharedWorkspace.LaunchApplication(path);
        }
    
        NSApplication.SharedApplication.Terminate(this);
    
    }