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 to do this?
Asked
Active
Viewed 3,216 times
8

Nick
- 10,309
- 21
- 97
- 201
-
1What are the solutions you have tried? – BoltClock Jun 16 '12 at 16:22
-
I tried to write a key registry: HKCU\Software\Microsoft\Windows\CurrentVersion\Run – Nick Jun 16 '12 at 16:25
-
And do you have any logging? In any case, what do you store in the registry key? That solution should work. – Marcel N. Jun 16 '12 at 16:27
-
Yes, I hav to log, this is my code: `RegistryKey app = Registry.CurrentUser.OpenSubKey("HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); app.SetValue("timer", AppDomain.CurrentDomain.BaseDirectory);` – Nick Jun 16 '12 at 16:29
-
BaseDirectory? You also need to include the executable you wish to start. BaseDirectory just returns the directory, it does not include the exe itself. – Christophe Geers Jun 16 '12 at 16:30
1 Answers
19
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.

Christophe Geers
- 8,564
- 3
- 37
- 53
-
[Application](http://msdn.microsoft.com/en-us/library/system.windows.application_members(v=vs.90)) has not ExecutablePath. – Nick Jun 16 '12 at 16:33
-
This sample code is for a Windows Forms application. You need to get the path to the executable in a different manner for WPF apps. – Christophe Geers Jun 16 '12 at 16:34
-
It works! If I want to remove this behavior, have I to remove the key? Could you show me how? – Nick Jun 16 '12 at 16:48
-
Idd, you only have to remove the key. I've already included this in my answer. – Christophe Geers Jun 16 '12 at 16:53
-
3