.NET实现:将EXE设置开机自动启动
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文件