How to Run a C# Application at Windows Startup

How do I set a program to launch at startup

Several options, in order of preference:

  1. Add it to the current user's Startup folder. This requires the least permissions for your app to run, and gives the user the most control and feedback of what's going on. The down-side is it's a little more difficult determining whether to show the checkbox already checked next time they view that screen in your program.
  2. Add it to the HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
  3. Create a Scheduled Task that triggers on User Login
  4. Add it to the HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
  5. Set it up as a windows service. Only do this if you really mean it, and you know for sure you want to run this program for all users on the computer.

This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the Startup folder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations.

How to run a C# application at Windows startup (update)?

Doing some research, I found that it's a much better way to create a shortcut and place it in the Startup folder. More details are presented here and the code (which works and solves the problem) is:

        WshShell wshShell = new WshShell();
IWshRuntimeLibrary.IWshShortcut shortcut;
string startUpFolderPath =
Environment.GetFolderPath(Environment.SpecialFolder.Startup);

// Create the shortcut
shortcut =
(IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(
startUpFolderPath + "\\" +
Application.ProductName + ".lnk");

shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Description = "Launch My Application";
// shortcut.IconLocation = Application.StartupPath + @"\App.ico";
shortcut.Save();

To be able to use the above code, you need to include the IWshRuntimeLibrary namespace and add the Windows Script Host Object Model reference to the project.

Other reference is here

How do i run a program on startup? c#

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

Run .net core app as windows application and start at windows startup

You have multiple options here.

  1. One is to add a registry key. (you should have permission for this)

    RegistryKey registryKeyk = Registry.CurrentUser.OpenSubKey
    ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

    registryKeyk.SetValue("AppName", Application.ExecutablePath);

  2. You can run the exe from Task Scheduler.

How To Run App.exe On Windows Startup Before Login? (Execute WinForm Before Login & Show Executed Form After Login For Interact = Show GUI)

You need to separate the services of your application from UI.

  • The service could be a Windows Service or a console application which runs before startup.
  • The UI could be a Windows Forms Application which runs after user login.
  • To communicate between the service and the windows Application, you can use an IPC solution, like self-hosted WCF or self-hosted Web API.

GUI application + WCF Service hosted in Windows Service + Installer

Here I'll share a step by step by step example including:

  • A Windows Service
  • A WCF Service hosted in Windows Service
  • A WinForms application which calls methods of the WCF service
  • An installer which installs windows service and the WinForms application and put the application in startup.

As a result, after installation the service will be started in windows startup. The GUI application also will start when user logs into the application. Then if you click on a button it will show a message from service.

Clone or Download:

  • r-aghaei/SampleUIandService
  • Download master.zip

ServiceLayer Project

  1. Create a class library project (ServiceLayer)

  2. Add a new WCF service to the class library. (MyWCFService)

  3. Modify the contract:

    [ServiceContract]
    public interface IMyWCFService
    {
    [OperationContract]
    string Echo(string message);
    }
  4. Modify the implementation of MyWCFService:

    public class MyWCFService : IMyWCFService
    {
    public string Echo(string message)
    {
    return message;
    }
    }
  5. Add a Windows Service. (MyWindowsService)

  6. Modify the implementation of the service:

    partial class MyWindowsService : ServiceBase
    {
    ServiceHost host;
    public MyWindowsService()
    {
    InitializeComponent();
    }
    protected override void OnStart(string[] args)
    {
    host = new ServiceHost(typeof(MyWCFService));
    host.Open();
    }
    protected override void OnStop()
    {
    host.Close();
    }
    }
  7. Double click on MyWindowsService, then right-click on the surface and choose Add Installer

  8. Double click on ProjectInstaller.cs and from list of components, choose serviceInstaller1, Then in properties window, set StartType to automatic.

  9. Choose serviceProcessInstaller1 and then in properties window, set Account to LocalSystem.

  10. Add a C# file. (Program.cs)

  11. Modify the content of Program.cs class to:

    static class Program
    {
    static void Main()
    {
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
    new MyWindowsService()
    };
    ServiceBase.Run(ServicesToRun);
    }
    }

UILayer Project

  1. Create a Windows Forms Application (UILayer)

  2. Add reference to MyServiceLayer project

  3. Open Form1 in design mode, drop a button on it and double click to handle its click event and use the following code:

    private void button1_Click(object sender, EventArgs e)
    {
    ChannelFactory<IMyWCFService> factory =
    new ChannelFactory<IMyWCFService>("BasicHttpBinding_IMyWCFService");
    IMyWCFService proxy = factory.CreateChannel();
    MessageBox.Show(proxy.Echo("Hello!"));
    }
  4. Modify the app.config file to include WCF configurations:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
    <system.serviceModel>
    <bindings>
    <basicHttpBinding>
    <binding name="BasicHttpBinding_IMyWCFService" />
    </basicHttpBinding>
    </bindings>
    <client>
    <endpoint address="http://localhost:8733/Design_Time_Addresses/ServiceLayer/MyWCFService/"
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyWCFService"
    contract="ServiceLayer.IMyWCFService" name="BasicHttpBinding_IMyWCFService" />
    </client>
    </system.serviceModel>
    </configuration>
  5. Make sure the endpoint address in app.config of UILayer is same as baseAddress in app.config of ServiceLayer.

Setup Project

  1. Create a Setup project.
  2. Right-click on project and from Add menu, choose Project output. Then add primary output of the ServiceLayer. (Choose project from dropdown)
  3. Right-click on project and from Add menu, choose Project output. Then add primary output of the UILayer.
  4. Right click on Setup project and choose view Custom Actions.
  5. In custom action windows, for all the nodes (Install, commit, rollback, uninstall), right-click and choose Add custom action and from the application folder, choose primary output of ServiceLayer.
  6. Right click on setup project and choose View FileSystem.
  7. Right click on the root node and choose Add special folder and choose User's startup folder.
  8. Choose Startup folder and then in right pane, right-click and choose create shortcut and from the application folder, choose primary output of UILayer.
  9. Rebuild the solution and setup project.
  10. Install setup by going to out put folder of setup or by right-click on setup project and choosing install.

After the installation is done, you may want to restart the system to see the effect. The service will be started automatically, and the UILayer will be shown after user logon.

Click on the button and it will show a MessageBox saying Hello! This content is coming from service.



Related Topics



Leave a reply



Submit