Search code examples
c#windowsstartup

How do i run a program on startup? c#


i'm developing an application with c#. I'd like to run the application on startup without having administrator privileges. I managed to run it on startup by copying the application itself on the startup folder but it required administrator privileges to do it. Could you please tell me how i may do it without administrator privileges?

Thanks and sorry for bad english, i'm not native


Solution

  • As a non-admin, you can only set something to startup automatically for your own user account. You would use the per-user startup folder (or one of the HKCU registry keys) for this.

    FOLDERID_CommonStartup

    For all users, requires admin privileges to modify. Location depends on OS version and customization, but by default is either: %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp %ALLUSERSPROFILE%\Start Menu\Programs\StartUp

    For C#, you can retrieve the path with Environment.GetFolderPath(SpecialFolder.CommonStartup).

    FOLDERID_Startup

    Per-user startup. Location depends on OS version and customization, but by default is either: %APPDATA%\Microsoft\Windows\Start Menu\Programs\StartUp %USERPROFILE%\Start Menu\Programs\StartUp

    For C#, you can retrieve the path with Environment.GetFolderPath(SpecialFolder.Startup). You'd normally want to place a shortcut to your app here, but there is no managed API for this so you'll need to pinvoke or have your installer create one for you.

    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run

    For all users, requires admin privileges to modify. For C#, can add an entry using the static Microsoft.Win32.Registry class.

    HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

    Per user. To add a new entry:

    const string HKCU = "HKEY_CURRENT_USER";
    const string RUN_KEY = @"SOFTWARE\\Microsoft\Windows\CurrentVersion\Run";
    string exePath = System.Windows.Forms.Application.ExecutablePath;
    Microsoft.Win32.Registry.SetValue(HKCU + "\\" + RUN_KEY, "AppName", exePath);