C#程序注销、重启、关机和锁定电脑

一:截图

二:源代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace 关机一键锁定
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        //关机
        private void btnShutDown_Click(object sender, RoutedEventArgs e)
        {

            //Process p = new Process();//实例化一个独立进程
            //p.StartInfo.FileName = "shutdown";
            //p.StartInfo.Arguments = "-s -t 0";
            //p.Start();//启动


            //等价于上面四句
            Process.Start("shutdown", "-s -t 0");
           
        }
        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
           //重启
            Process.Start("shutdown", "-r -t 0");
        }

        private void btnUnlogin_Click(object sender, RoutedEventArgs e)
        {
            //注销
            Process.Start("shutdown", "-l ");//C#写的关机、重启、注销程序,代码简单主要是用Process类来操作
        }

        [DllImport("User32.DLL")]
        public static extern void LockWorkStation();
        //一键锁定
        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            LockWorkStation();
        }
        //打开CMD窗口
        private void btnCMD_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("cmd");
        }
    }
}

三:结语

当然我这样做不是为了方便大家关机、重启、注销和锁定、打开CMD窗口使用,微软为大家提供很方便的快捷键,如:win+r ,win+l等,不要再吐槽者方面了,仅供娱乐的代码

原文地址:https://www.cnblogs.com/hongmaju/p/3939796.html