当您说必须向注册表添加一个密钥时,您是正确的。
添加一个键:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
如果您想为当前用户启动应用程序。
Or:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
如果您想为所有用户启动它。
例如,为当前用户启动应用程序:
var path = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
RegistryKey key = Registry.CurrentUser.OpenSubKey(path, true);
key.SetValue("MyApplication", Application.ExecutablePath.ToString());
只需将第二行替换为
RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true);
如果您想在 Windows 启动时自动为所有用户启动该应用程序。
如果您不想再自动启动应用程序,只需删除注册表值即可。
As such:
var path = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
RegistryKey key = Registry.CurrentUser.OpenSubKey(path, true);
key.DeleteValue("MyApplication", false);
此示例代码针对 WinForms 应用程序进行了测试。如果您需要确定 WPF 应用程序的可执行文件的路径,请尝试以下操作。
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
只需将“Application.ExecutablePath.ToString()”替换为可执行文件的路径即可。