一.原理解释
在winform应用程序开发过程中会有开机自启动功能。
如上图所示,勾选复选框时,软件会在下次电脑开机时自启动。要实现开机自启动功能主要是对电脑的注册表进行操作,需要在计算机注册表的该路径下“HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run”执行写入。C#提供了注册表相关的类,包含在Microsoft.Win32命名空间,本次主要使Registry类和RegistryKey类。
二.具体代码
private void chbox_test_CheckStateChanged(object sender, EventArgs e)
{
//获取当前的windows用户
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
//名称和值
string keyName = Assembly.GetExecutingAssembly().GetName().Name;
string keyValue = Assembly.GetExecutingAssembly().Location;
//新建一个RegistryKey对象
RegistryKey registryKey = null;
//判断复选框是否选中
if (chbox_test.CheckState == CheckState.Checked)
{
//判断当前用户是否是管理员
if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
try
{
//打开注册表指定项,写入值
registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
registryKey.SetValue(keyName, keyValue);
}
catch
{
MessageBox.Show("注册表写失败", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
//关闭该项
registryKey.Close();
}
}
else
{
try
{
//以管理员身份重启该程序
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = Assembly.GetExecutingAssembly().CodeBase;
processStartInfo.UseShellExecute = true;
processStartInfo.Verb = "runas";
if (Process.Start(processStartInfo) != null)
{
Environment.Exit(0);
}
}
catch
{
MessageBox.Show("重启软件失败", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else
{
try
{
//打开注册表指定项,删除值
registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
registryKey.DeleteValue(keyName, false);
}
catch
{
MessageBox.Show("注册表删除失败", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
//关闭该项
registryKey.Close();
}
}
}
三.注意事项
1.操作注册表一般会有权限限制,因此要在操作之前需要判断当前windows用户权限等级,否则无法成功写注册表。