代碼如下:
private void btnSetOk_Click(object sender, EventArgs e)
{
RegCompStartRun(true, txtFullPath.Text.Trim());
}
private void btnCancel_Click(object sender, EventArgs e)
{
RegCompStartRun(false, txtFullPath.Text.Trim());
}
private void RegCompStartRun(bool cmd, string argPath)
{
string starupPath = argPath;
if (string.IsNullOrEmpty(argPath))
{
//獲取當前可執行程序的全路徑
starupPath = Application.ExecutablePath;
}
//表示Window注冊表中項級節點,讀取 Windows 注冊表基項HKEY_LOCAL_MACHINE
Microsoft.Win32.RegistryKey loca = Microsoft.Win32.Registry.LocalMachine;
Microsoft.Win32.RegistryKey run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
try
{
//SetValue:存儲值的名稱
if (cmd)
{
run.SetValue("AutoStartupTestWinFormApp", starupPath);//加入注冊,參數一為注冊節點名稱(隨意)
lblDisplay.Text = "設置成功!";
}
else
{
run.DeleteValue("AutoStartupTestWinFormApp", false);//刪除該注冊節點
lblDisplay.Text = "取消設置成功!";
}
loca.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
注意事項:
如果設置後,重命名該exe文件,則注銷、重啟後重新登錄,設置的開機啟動項不會啟動,
如果改回原來的名字,則再次注銷或重啟,登錄後會自動啟動該設置的exe文件