作为小白,本人在互联网中获取到了两种利用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()
以上的两种方法都需要创建窗口程序