Launch Window on Windows startup

半城伤御伤魂 提交于 2019-11-30 13:48:43

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!