关于利用C#实现windows的自动关机

作为小白,本人在互联网中获取到了两种利用C#实现windows的自动关机方法

public partial class Form1 : Form
{
    
        /// <summary>
        /// 关机定时
        /// </summary>
        private DispatcherTimer shutdown;

        public Form1()
        {
            InitializeComponent();

            WindowStartupLocation s= WindowStartupLocation.CenterScreen;
            shutdown = new DispatcherTimer();
            shutdown.Tick += new EventHandler(ShowCurTimer);
            shutdown.Interval = new TimeSpan(0, 0, 0, 1, 0);
            shutdown.Start();
            try
            {
            }
            catch (Exception)
            {
                //this.Dispatcher.Invoke(new Action(delegate { this.Close(); }));
            }
        }

        #region 执行关机
        public void ShowCurTimer(object sender, EventArgs e)
        {
            关机();
        }
        private void 关机()
        {
            System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo();
            ps.FileName = "shutdown.exe";
            ps.Arguments = "-s -t 0"; System.Diagnostics.Process.Start(ps);
        }
        #endregion

    }
}

这是第一种利用“ShowCurTImer”

namespace close1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            string ss = APIHelper.DOSCommand("shutdown -s -t 0");
          
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            string ss = APIHelper.DOSCommand("shutDown -r -t 0");
            
        }
    }
}
enum UFlag
{
    EWX_FORCE = 4,
    EWX_LOGOFF = 0,
    EWX_REBOOT = 2,
    EWX_SHUTDOWN = 1
}
class APIHelper

{
    public static string DOSCommand(string cmdStr)
    {
        ProcessStartInfo info = new ProcessStartInfo();
        info.CreateNoWindow = true;
        info.FileName = "cmd.exe";
        info.RedirectStandardError = true;
        info.RedirectStandardOutput = true;
        info.RedirectStandardInput = true;
        info.UseShellExecute = false;
        var p = Process.Start(info);
        p.StandardInput.WriteLine(cmdStr + "&exit");
        p.WaitForExit();
        string str = "";
        using (System.IO.TextReader tr = p.StandardOutput)
        {
            str = tr.ReadToEnd();
        }
        p.Close();
        return str;
    }
    public static int ExitWindows(UFlag flag)
    {
        return ExitWindowsEx((int)flag, 0);
    }
    [DllImport("user32.dll")]
    extern static int ExitWindowsEx(int UFlag, int dwReserved);
}


这是第二中,利用Process.Start()

 以上的两种方法都需要创建窗口程序

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值