方法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;
}