I want that my application (a WPF Window
) is launched on Windows startup. I tried different solutions, but no one seems to work. What i have to write in my code
You are correct when you say that you must add a key to the registry.
Add a key to:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
if you want to start the application for the current user.
Or:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
If you want to start it for all users.
For example, starting the application for the current user:
var path = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
RegistryKey key = Registry.CurrentUser.OpenSubKey(path, true);
key.SetValue("MyApplication", Application.ExecutablePath.ToString());
Just replace the line second line with
RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true);
if you want to automatically start the application for all users on Windows startup.
Just remove the registry value if you no longer want to start the application automatically.
As such:
var path = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
RegistryKey key = Registry.CurrentUser.OpenSubKey(path, true);
key.DeleteValue("MyApplication", false);
This sample code was tested for a WinForms app. If you need to determine the path to the executable for a WPF app, then give the following a try.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
Just replace "Application.ExecutablePath.ToString()" with the path to your executable.