C# 程序设定开机启动
时间: 2023-10-19 16:53:46 浏览: 80
要在 C# 程序中将应用程序设为开机启动,你可以使用 `Microsoft.Win32` 命名空间中的 `Registry` 类来修改注册表。下面是一个示例代码:
```csharp
using Microsoft.Win32;
using System;
class Program
{
static void Main()
{
string appName = "MyApp"; // 应用程序的名称
string appPath = "C:\\Path\\To\\Your\\Application.exe"; // 应用程序的路径
// 创建或打开注册表项
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
try
{
// 设置开机启动项
rk.SetValue(appName, appPath);
Console.WriteLine("已将应用程序设置为开机启动。");
}
catch (Exception ex)
{
Console.WriteLine("设置开机启动时出错:" + ex.Message);
}
// 关闭注册表项
rk.Close();
Console.ReadLine();
}
}
```
上述代码中,我们使用 `Registry.CurrentUser.OpenSubKey()` 方法打开 `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run` 注册表项,该项存储了当前用户的开机启动项。然后,我们使用 `SetValue()` 方法将应用程序的名称和路径设置为注册表项的值。
请注意,你需要将 `appName` 替换为你的应用程序的名称,`appPath` 替换为你的应用程序的完整路径。
运行上述代码后,应用程序将被添加到开机启动项中。在每次用户登录时,应用程序都会自动启动。
如果你想要从开机启动项中移除应用程序,可以使用 `RegistryKey.DeleteValue()` 方法。例如:
```csharp
rk.DeleteValue(appName);
```
以上代码将从注册表中删除指定的开机启动项。
请注意,修改注册表需要管理员权限。确保以管理员身份运行你的应用程序,或者在运行时获得管理员权限。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)