Monday, September 3, 2012

Start Program Automatically on Windows Startup

In this post I want to show, how to add a C# program to the autostart of Windows.
For this there are 2 possibilites: One the one hand, we can add a shortcut to the program in the startup folder, on the other hand we can create an entry in the registry.


1. Method: Create Shortcut
How to create a shortcut in general, I described in that post. We now have to set our program as link target and as path the startup folder of Windows, which is located under Windows 7 in C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup. The path to our own application we get by Application.ExecutablePath.ToString() - so the following code copies the program to the startup folder (as icon we can set an icon):
CreateShortcut(@"C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" + "\\CAutoStart.url",  Application.ExecutablePath.ToString(), "C:\\MeinIcon.ico");


2. Method: Create Registry Entry
The analogon to above path is located in the registry under HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run. How to use the registry in general with C#, is described in this tutorial. Here I just show the complete code, which creates the needed entry so that the application starts automatically when Windows starts:
RegistryKey AutostartKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
AutostartKey.SetValue("CAutoStart", Application.ExecutablePath.ToString());
AutostartKey.Close();

No comments:

Post a Comment