C#中设置开机自动运行和关机

 让软件开机自动运行或者设置自动关机,大部分软件都有这种功能。如何实现呢,其实很简单,开机运行,只需要设置注册表就可以了,关机则调用CMD命令:shutdown -s -t,如下:
开机自动运行:

        /// <summary>          /// 设置开机运行           /// </summary>          public void AutoRun()          {              RegistryKey runItem =              Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);                if (runItem == null)              {                  run.SetValue("exe的名字","exe的路径");              }          }          /// <summary>          /// 取消开机运行           /// </summary>          public void DeleteAutoRun()          {              RegistryKey runItem =              Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);                if (runItem != null)              {                  runItem.DeleteSubKey("exe的名字");              }          }  

设置关机:

        public static string ExecuteCmd(string command)          {              string output = ""; //输出字符串                 if (command != null && !command.Equals(""))              {                  Process process = new Process();//创建进程对象                     ProcessStartInfo startInfo = new ProcessStartInfo();                  startInfo.FileName = "cmd.exe";//设定需要执行的命令                     startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出                     startInfo.UseShellExecute = false;//不使用系统外壳程序启动                     startInfo.RedirectStandardInput = false;//不重定向输入                     startInfo.RedirectStandardOutput = true; //重定向输出                     startInfo.CreateNoWindow = true;//不创建窗口                     process.StartInfo = startInfo;                  process.Start();              }          }

调用:

ExecuteCmd("shutdown -s -t");


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值