1、重启系统:
(1)利用dos命令对应的可执行程序
public static void RestartOS(out string errorDesc)
{
try
{
errorDesc = string.Empty;//---重启系统---
string tmpFileName = "shutdown.exe";
string tmpCmdLineParameters = "-r -t 0 -f";System.Diagnostics.Process tmpShutdownProc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo tmpStartInfo =
new System.Diagnostics.ProcessStartInfo(tmpFileName, tmpCmdLineParameters);
tmpStartInfo.UseShellExecute = false;//加上这一句,否则在重启系统时会有个对话框已关闭的错误框弹出
tmpShutdownProc.StartInfo = tmpStartInfo;tmpShutdownProc.Start();
}
catch (Exception allE)
{
errorDesc = allE.Message;
}
}(2)利用WMI
(3)利用API
2、开机自动自动执行当前应用程序
public static void AddCurrentExeToRegisterRunOnce(out string errorDesc)
{
try
{
errorDesc = string.Empty;//---添加注册表---
Microsoft.Win32.RegistryKey tmpRegKey =
Microsoft.Win32.Registry.CurrentUser;
tmpRegKey = tmpRegKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\RunOnce", true);
tmpRegKey.SetValue(@"tmp", Application.ExecutablePath);
}
catch (Exception allE)
{
errorDesc = allE.Message;
}
}注:注册表中允许开机自动执行的注册键不止这一个,之所以用这一个,是因为它具有“只在下次开机时运行一次,并且是在整个用户程序加载完成后运行指定的程序。”
感兴趣的可以试一下用这个键值在HKEY_LOCAL_MACHINE下面的同名键(即Software\Microsoft\Windows\CurrentVersion\RunOnce),实际感受他们之间的区别;