8

我希望我的应用程序(一个 WPF Window)在 Windows 启动时启动。我尝试了不同的解决方案,但似乎没有一个有效。我必须在我的代码中写什么来做到这一点?

4

1 回答 1

16

当您说必须向注册表添加密钥时,您是正确的。

将密钥添加到:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

如果要为当前用户启动应用程序。

或者:

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 启动时为所有用户自动启动应用程序。

如果您不想再自动启动应用程序,只需删除注册表值。

像这样:

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()”替换为可执行文件的路径即可。

于 2012-06-16T16:29:31.553 回答