C#中如何重启系统并在开机后自动执行当前可执行程序

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),实际感受他们之间的区别;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值