c#开机自启关闭
时间: 2023-07-27 15:22:12 浏览: 58
你可以通过以下步骤实现 C# 程序的开机自启和关闭:
开机自启:
1. 打开 C# 项目,右键点击项目名称,选择“添加” -> “新建项” -> “应用程序清单文件”。
2. 在清单文件中添加以下代码:
```
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
<requestedExecutionLevel level="requireAdministrator" />
<application>
<runAtStartup>true</runAtStartup>
</application>
</startup>
```
3. 在项目中添加 System.Management.dll 引用。
4. 在代码中添加以下代码:
```
using System.Management;
private void SetAutoRun(string name, string path)
{
ManagementClass mgmtClass = new ManagementClass("Win32_StartupCommand");
ManagementBaseObject inParams = mgmtClass.GetMethodParameters("Create");
inParams["Name"] = name;
inParams["Command"] = path;
inParams["Location"] = "HKLM";
mgmtClass.InvokeMethod("Create", inParams, null);
}
```
5. 调用 SetAutoRun 方法,传入要启动的程序名称和路径即可。
关闭自启:
1. 打开 C# 项目,右键点击项目名称,选择“添加” -> “新建项” -> “应用程序清单文件”。
2. 在清单文件中添加以下代码:
```
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
<requestedExecutionLevel level="requireAdministrator" />
<application>
<uninstallShortcut>true</uninstallShortcut>
</application>
</startup>
```
3. 在代码中添加以下代码:
```
using System.Management;
private void RemoveAutoRun(string name)
{
ManagementClass mgmtClass = new ManagementClass("Win32_StartupCommand");
ManagementObjectCollection mgmtCollection = mgmtClass.GetInstances();
foreach (ManagementObject mgmtObject in mgmtCollection)
{
if (mgmtObject["Name"].ToString().ToLower() == name.ToLower())
{
mgmtObject.Delete();
break;
}
}
}
```
4. 调用 RemoveAutoRun 方法,传入要关闭自启的程序名称即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)