C# winform程序开机自启的方法

 

方法1:修改注册表(好处在于即使程序需要管理员权限也能正常开启,并显示页面)
using Microsoft.Win32; //添加引用->COM,搜索Windows Script Host Object Model
try
{
if (checkBox1.Checked)
{
RegistryKey r_local = Registry.LocalMachine;//registrykey r_local = registry.currentuser;
RegistryKey r_run = r_local.CreateSubKey(@"software\microsoft\windows\currentversion\run");
r_run.SetValue("应用名称", Application.ExecutablePath);
r_run.Close();
r_local.Close();
}
else
{
RegistryKey r_local = Registry.LocalMachine;//registrykey r_local = registry.currentuser;
RegistryKey r_run = r_local.CreateSubKey(@"software\microsoft\windows\currentversion\run");
r_run.DeleteValue("应用名称", false);
r_run.Close();
r_local.Close();
}
}
catch (Exception)
{
MessageBox.Show("您需要管理员权限修改", "提示");
}

//检查是否开机自启
RegistryKey r_local = Registry.LocalMachine;//registrykey r_local = registry.currentuser;
RegistryKey r_run = r_local.OpenSubKey(@"software\microsoft\windows\currentversion\run", false);
if (r_run.GetValue("ServiceManageCenter") != null)
{
checkBox1.Checked = true;
}
r_run.Close();
r_local.Close();

 

方法2:将程序的启动文件制作一份快捷方式放进windows启动目录下
(好处是简单,不用改注册表,安全;坏处是winform界面无法显示出来,不知道是不是因为需要管理员权限的原因)
using IWshRuntimeLibrary;
if (checkBox1.Checked)
{
string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
//获得文件的当前路径
string dir = Directory.GetCurrentDirectory();
//获取可执行文件的全部路径
string exeDir = dir + @"\ServiceManageCenter.exe";
WshShell wshShell = new WshShell();
string path = System.IO.Path.Combine(StartupPath, "ServiceManageCenter.lnk");
IWshShortcut shortcut = (IWshShortcut)wshShell.CreateShortcut(path);
shortcut.TargetPath = exeDir;
shortcut.WorkingDirectory = dir;
shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口
shortcut.Save();
}
else
{
string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
System.IO.File.Delete(StartupPath + @"\ServiceManageCenter.lnk");
}

 

//检查是否开机自启
string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup) + @"\ServiceManageCenter.lnk";
if(System.IO.File.Exists(StartupPath))
{
checkBox1.Checked = true;
}

 

posted @ 2019-09-28 15:59  剑存古风  阅读(2994)  评论(0编辑  收藏  举报