Introduction
Have you ever wondered how to get your program to run automatically when you start your computer up? Well, a simple way to do so is by adding a shortcut of your program to the "Startup" directory of the current user's Start menu, but that's not very professional (though some programs do it that way). A better way is through the Registry, which allows easier access/removal of the startup item.
Using the Code
Now, since we are accessing the Registry, you will need to import Microsoft.Win32
, which contains the part of the .NET Framework that handles the Registry.
There are two different Registry directories that handle startup items: HKEY_Current_User
and HKEY_Local_Machine
. Current User will start the program for the current user only, and Local Machine will start the program for anyone who uses the computer.
To add a startup item to Current_User
, you will have to open the Registry key and set the value, like so:
Private Sub AddCurrentKey(ByVal name As String, ByVal path As String)
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(_
"Software\Microsoft\Windows\CurrentVersion\Run", True)
key.SetValue(name, path)
End Sub
And to remove it:
Private Sub RemoveCurrentKey(ByVal name As String)
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(_
"Software\Microsoft\Windows\CurrentVersion\Run", True)
key.DeleteValue(name, False)
End Sub
Now, I am using a checkbox to determine whether or not the Registry startup key is set. The "name" and "path" will be set when the function that sets the Registry value is called.
If CurrentStartup.Checked Then
AddCurrentKey("StartupExample", _
System.Reflection.Assembly.GetEntryAssembly.Location)
Else
RemoveCurrentKey("StartupExample")
End If
StartupExample is the name of the project, and will also be the name set in the Registry key. System.Reflection.Assembly.GetEntryAssembly.Location
gets the current location of the program to store in the Registry key. Also, another way that you can set the "name" of the startup key other than specifying it is by using System.Reflection.Assembly.GetEntryAssembly.FullName
.
Now, to set the same startup key in Local_Machine
, just change CurrentUser
to LocalMachine
.
Points of Interest
It is always a good idea to set the uninstaller for your program to remove all the Registry keys used by your program when uninstalling. This saves on Registry clutter, computer speed, and any risks of crashing when Windows tries to start a program up but can't find it because the Registry key wasn't removed.