C#代码设置开机启动示例

本文介绍了使用C#代码设置开机启动的方法,原理就是在注册表启动项里添加一项

在注册表启动项里添加一项,路径:SOFTWARE\Microsoft\Windows\CurrentVersion\Run
或者直接:运行->regedit找到这个路径添加一项。

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Microsoft.Win32;

namespace CSharpStart
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnSet_Click(object sender, EventArgs e)
{
SetAutoRun(@"D:\CSharpStart.exe",true);
}

/// 设置应用程序开机自动运行
/// 应用程序的文件名
/// 是否自动运行,为false时,取消自动运行
/// 设置不成功时抛出异常
public static void SetAutoRun(string fileName, bool isAutoRun)
{
RegistryKey reg = null;
try
{
if (!System.IO.File.Exists(fileName))
throw new Exception("该文件不存在!");
String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (reg == null)
reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
if (isAutoRun)
reg.SetValue(name, fileName);
else
reg.SetValue(name, false);
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
if (reg != null)
reg.Close();
}

}
//另外也可以写成服务,不过服务的话一般是在后台执行的,没有程序界面。 柯乐义

}
}

以上就是C#代码设置开机启动示例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程