C#中如何用代码实现计算机的重启?

比如我在Form里拉个button,在button里写什么代码可以使计算机重启和关闭!请那位高手指点一下!

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace TimerComputerShutdown
{
/// <summary>
/// Summary description for TimerComputerShutdown.
/// </summary>
public class TimerComputerShutdown : System.Windows.Forms.Form
{
private System.Windows.Forms.Label labelWhatDoYouWantTheComputerToDo;
private System.Windows.Forms.ComboBox comboBox;
private System.Windows.Forms.Label labelSelectDateTimeToShutdownComputer;
private System.Windows.Forms.DateTimePicker dateTimePicker;
private System.Windows.Forms.Label labelDateTimeNow;
private System.Windows.Forms.Label labelDateTimeShutdown;
private System.Windows.Forms.Label labelNow;
private System.Windows.Forms.Label labelShutdown;
private System.Windows.Forms.Panel panelParent;
private System.Windows.Forms.Panel panelChild;
private System.Windows.Forms.CheckBox checkBox;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Button buttonInvoke;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

private System.Threading.ThreadStart threadStart;
private System.Threading.Thread thread;

/// <summary>
/// 将窗口设为系统的前台窗口。这个函数可用于改变用户目前正在操作的应用程序
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
[DllImport("user32.dll")] private static extern
bool SetForegroundWindow(IntPtr hWnd);//将窗口设为系统的前台窗口。这个函数可用于改变用户目前正在操作的应用程序
/// <summary>
/// 更改某窗体状态,如最大化或还原
/// </summary>
/// <param name="hWnd"></param>
/// <param name="nCmdShow"></param>
/// <returns></returns>
[DllImport("user32.dll")] private static extern
bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);//更改某窗体状态,如最大化或还原
/// <summary>
/// 判断窗口是否已经最小化
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
[DllImport("user32.dll")] private static extern
bool IsIconic(IntPtr hWnd);//判断窗口是否已经最小化

private const int SW_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;

public TimerComputerShutdown()
{

InitializeComponent();

}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(TimerComputerShutdown));
this.labelWhatDoYouWantTheComputerToDo = new System.Windows.Forms.Label();
this.comboBox = new System.Windows.Forms.ComboBox();
this.labelSelectDateTimeToShutdownComputer = new System.Windows.Forms.Label();
this.dateTimePicker = new System.Windows.Forms.DateTimePicker();
this.labelDateTimeNow = new System.Windows.Forms.Label();
this.labelDateTimeShutdown = new System.Windows.Forms.Label();
this.labelNow = new System.Windows.Forms.Label();
this.labelShutdown = new System.Windows.Forms.Label();
this.panelParent = new System.Windows.Forms.Panel();
this.panelChild = new System.Windows.Forms.Panel();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonInvoke = new System.Windows.Forms.Button();
this.checkBox = new System.Windows.Forms.CheckBox();
this.panelParent.SuspendLayout();
this.panelChild.SuspendLayout();
this.SuspendLayout();
//
// labelWhatDoYouWantTheComputerToDo
//
this.labelWhatDoYouWantTheComputerToDo.Location = new System.Drawing.Point(8, 8);
this.labelWhatDoYouWantTheComputerToDo.Name = "labelWhatDoYouWantTheComputerToDo";
this.labelWhatDoYouWantTheComputerToDo.Size = new System.Drawing.Size(216, 16);
this.labelWhatDoYouWantTheComputerToDo.TabIndex = 9;
this.labelWhatDoYouWantTheComputerToDo.Text = "选择任务:";
this.labelWhatDoYouWantTheComputerToDo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// comboBox
//
this.comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox.Items.AddRange(new object[] {
"关机",
"重启",
"待机",
"睡眠",
"注销"});
this.comboBox.Location = new System.Drawing.Point(184, 8);
this.comboBox.Name = "comboBox";
this.comboBox.Size = new System.Drawing.Size(112, 21);
this.comboBox.TabIndex = 0;
this.comboBox.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// labelSelectDateTimeToShutdownComputer
//
this.labelSelectDateTimeToShutdownComputer.Location = new System.Drawing.Point(8, 32);
this.labelSelectDateTimeToShutdownComputer.Name = "labelSelectDateTimeToShutdownComputer";
this.labelSelectDateTimeToShutdownComputer.Size = new System.Drawing.Size(144, 16);
this.labelSelectDateTimeToShutdownComputer.TabIndex = 7;
this.labelSelectDateTimeToShutdownComputer.Text = "选择任务时间: ";
this.labelSelectDateTimeToShutdownComputer.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// dateTimePicker
//
this.dateTimePicker.CalendarFont = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.dateTimePicker.Cursor = System.Windows.Forms.Cursors.Arrow;
this.dateTimePicker.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.dateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.dateTimePicker.Location = new System.Drawing.Point(184, 32);
this.dateTimePicker.Name = "dateTimePicker";
this.dateTimePicker.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.dateTimePicker.Size = new System.Drawing.Size(112, 21);
this.dateTimePicker.TabIndex = 1;
this.dateTimePicker.Value = new System.DateTime(2002, 9, 27, 0, 0, 0, 0);
this.dateTimePicker.ValueChanged += new System.EventHandler(this.dateTimePicker_ValueChanged);
//
// labelDateTimeNow
//
this.labelDateTimeNow.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labelDateTimeNow.Location = new System.Drawing.Point(8, 8);
this.labelDateTimeNow.Name = "labelDateTimeNow";
this.labelDateTimeNow.Size = new System.Drawing.Size(120, 16);
this.labelDateTimeNow.TabIndex = 4;
this.labelDateTimeNow.Text = "当前时间:";
this.labelDateTimeNow.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelDateTimeShutdown
//
this.labelDateTimeShutdown.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labelDateTimeShutdown.Location = new System.Drawing.Point(8, 32);
this.labelDateTimeShutdown.Name = "labelDateTimeShutdown";
this.labelDateTimeShutdown.Size = new System.Drawing.Size(120, 16);
this.labelDateTimeShutdown.TabIndex = 5;
this.labelDateTimeShutdown.Text = "任务时间:";
this.labelDateTimeShutdown.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelNow
//
this.labelNow.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labelNow.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelNow.Location = new System.Drawing.Point(136, 8);
this.labelNow.Name = "labelNow";
this.labelNow.Size = new System.Drawing.Size(136, 16);
this.labelNow.TabIndex = 1;
this.labelNow.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// labelShutdown
//
this.labelShutdown.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labelShutdown.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelShutdown.Location = new System.Drawing.Point(136, 32);
this.labelShutdown.Name = "labelShutdown";
this.labelShutdown.Size = new System.Drawing.Size(136, 16);
this.labelShutdown.TabIndex = 8;
this.labelShutdown.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// panelParent
//
this.panelParent.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelParent.Controls.Add(this.panelChild);
this.panelParent.Location = new System.Drawing.Point(8, 60);
this.panelParent.Name = "panelParent";
this.panelParent.Size = new System.Drawing.Size(288, 60);
this.panelParent.TabIndex = 6;
//
// panelChild
//
this.panelChild.Controls.Add(this.labelNow);
this.panelChild.Controls.Add(this.labelShutdown);
this.panelChild.Controls.Add(this.labelDateTimeShutdown);
this.panelChild.Controls.Add(this.labelDateTimeNow);
this.panelChild.Location = new System.Drawing.Point(0, 0);
this.panelChild.Name = "panelChild";
this.panelChild.Size = new System.Drawing.Size(280, 56);
this.panelChild.TabIndex = 8;
//
// buttonCancel
//
this.buttonCancel.Cursor = System.Windows.Forms.Cursors.Hand;
this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonCancel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.buttonCancel.Location = new System.Drawing.Point(176, 128);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(56, 23);
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "取消&C";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonInvoke
//
this.buttonInvoke.Cursor = System.Windows.Forms.Cursors.Hand;
this.buttonInvoke.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonInvoke.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.buttonInvoke.Location = new System.Drawing.Point(240, 128);
this.buttonInvoke.Name = "buttonInvoke";
this.buttonInvoke.Size = new System.Drawing.Size(56, 23);
this.buttonInvoke.TabIndex = 3;
this.buttonInvoke.Text = "确定&O";
this.buttonInvoke.Click += new System.EventHandler(this.buttonInvoke_Click);
//
// checkBox
//
this.checkBox.Cursor = System.Windows.Forms.Cursors.Hand;
this.checkBox.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkBox.Location = new System.Drawing.Point(8, 128);
this.checkBox.Name = "checkBox";
this.checkBox.Size = new System.Drawing.Size(66, 24);
this.checkBox.TabIndex = 2;
this.checkBox.Text = "强制&B";
//
// TimerComputerShutdown
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.BackColor = System.Drawing.Color.GhostWhite;
this.ClientSize = new System.Drawing.Size(306, 159);
this.Controls.Add(this.checkBox);
this.Controls.Add(this.comboBox);
this.Controls.Add(this.labelWhatDoYouWantTheComputerToDo);
this.Controls.Add(this.panelParent);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonInvoke);
this.Controls.Add(this.dateTimePicker);
this.Controls.Add(this.labelSelectDateTimeToShutdownComputer);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "TimerComputerShutdown";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Timer Computer Shutdown";
this.TopMost = true;
this.Load += new System.EventHandler(this.TimerComputerShutdown_Load);
this.panelParent.ResumeLayout(false);
this.panelChild.ResumeLayout(false);
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new TimerComputerShutdown());
}

private void TimerComputerShutdown_Load(object sender, System.EventArgs e)
{
this.threadStart = new System.Threading.ThreadStart(Application_Tick);
this.thread = new System.Threading.Thread(threadStart);

this.panelChild.Visible = false;

this.dateTimePicker.Value = System.DateTime.Now;
}

protected override void OnClosing(CancelEventArgs e)
{
try
{
if (this.thread.IsAlive)
{
this.thread.Abort();
this.thread.Join();
}
}
catch (System.Threading.ThreadAbortException threadAbortException)
{
System.Threading.Thread.ResetAbort();
}
catch (System.Exception exception)
{

}
finally
{
System.Windows.Forms.Application.Exit();
}

base.OnClosing(e);
}

public void Computer_Shutdown()
{
if (this.checkBox.Checked)
{
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();

foreach (System.Diagnostics.Process processParent in processes)
{
System.Diagnostics.Process[] processNames = System.Diagnostics.Process.GetProcessesByName(processParent.ProcessName);

foreach (System.Diagnostics.Process processChild in processNames)
{
try
{
System.IntPtr hWnd = processChild.MainWindowHandle;

if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}

SetForegroundWindow(hWnd);

if (!(processChild.MainWindowTitle.Equals(this.Text)))
{
processChild.CloseMainWindow();
processChild.Kill();
processChild.WaitForExit();
}
}
catch (System.Exception exception)
{

}
}
}
}

System.Windows.Forms.Application.Exit();

switch (this.comboBox.SelectedIndex)
{
case 0:
WindowsController.ExitWindows(RestartOptions.PowerOff, false);
break;
case 1:
WindowsController.ExitWindows(RestartOptions.Reboot, false);
break;
case 2:
WindowsController.ExitWindows(RestartOptions.Suspend, false);
break;
case 3:
WindowsController.ExitWindows(RestartOptions.Hibernate, false);
break;
case 4:
WindowsController.ExitWindows(RestartOptions.LogOff, false);
break;
}
}

private void comboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.labelSelectDateTimeToShutdownComputer.Text = "选择任务" + " " + this.comboBox.SelectedItem.ToString() + " " + "时间:";
this.labelDateTimeShutdown.Text = "任务时间" + " " + this.comboBox.SelectedItem.ToString() + ":";
}

public bool dateTimePicker_Validated()
{
if (this.dateTimePicker.Value.CompareTo(System.DateTime.Now) < 0)
{
//Error error = new Error();
//error.ShowDialog();

this.dateTimePicker.Value = System.DateTime.Now;

return false;
}
else
{
return true;
}
}

private void dateTimePicker_ValueChanged(object sender, System.EventArgs e)
{
this.labelShutdown.Text = this.dateTimePicker.Value.ToString();
}

public void Application_Tick()
{
while (!(this.labelNow.Text.ToString().Equals(this.dateTimePicker.Value.ToString())))
{
this.labelNow.Text = System.DateTime.Now.ToString();
}

this.Computer_Shutdown();
}

private void buttonCancel_Click(object sender, System.EventArgs e)
{
try
{
if (this.thread.IsAlive)
{
this.thread.Abort();
this.thread.Join();
}
}
catch (System.Threading.ThreadStateException threadStateException)
{
System.Threading.Thread.ResetAbort();
}
catch (System.Exception exception)
{

}
finally
{
System.Windows.Forms.Application.Exit();
}
}

private void buttonInvoke_Click(object sender, System.EventArgs e)
{
if (this.dateTimePicker_Validated())
{
this.thread.Start();

this.comboBox.Enabled = false;
this.dateTimePicker.Enabled = false;
this.panelChild.Visible = true;
this.buttonInvoke.Enabled = false;
}
}
}
}

参考资料:自己以前的例子慢慢看吧

温馨提示:内容为网友见解,仅供参考
第1个回答  2008-07-08
.net类库没有直接操作计算机重启的类库

你可以用Proccess类启动外部应用程序(比如shutdown)或者调用系统函数才可以
这种操作要求安全性很高,所以也不容易做到

C#中如何用代码实现计算机的重启?
.net类库没有直接操作计算机重启的类库你可以用Proccess类启动外部应用程序(比如shutdown)或者调用系统函数才可以这种操作要求安全性很高,所以也不容易做到 已赞过 已踩过< 你对这个回答的评价是? 评论 收起 其他类似问题 2017-03-10 C# 实现重启他人计算机的代码 2 2018-08-03 C#控制台程序如何用代码实现自...

C# 实现重启他人计算机的代码
\/\/\/ \/\/\/ 远程关闭计算机或重启计算机\/\/\/ \/\/\/ 命令\/\/\/ ip地址static void Invoke(string str, string ip){ \/\/定义连接远程计算机的一些选项 ConnectionOptions options = new ConnectionOptions(); options.Username = "administrator"; options.Password = "Btmu@123"; ManagementScope scope = new...

问下C#中怎么在程序里设置让电脑自动关机或者重启
C# 实现注销、关机、重启电脑功能 using System.Runtime.InteropServices;[Flags]public enum ExitWindows : uint { LogOff = 0x00, \/\/注销 ShutDown = 0x01, \/\/关机 Reboot = 0x02, \/\/重启 Force = 0x04,PowerOff = 0x08,ForceIfHung = 0x10 } [Flags]public enum ShutdownReason ...

“C# WinForm ”如何实现程序重启?
如果程序需要重启只需要在捕获的事件处理时启动当前应用程序的代码即可。参考如下:\/\/重启程序,需要时加上重启的参数System.Diagnostics.ProcessStartInfo cp = new System.Diagnostics.ProcessStartInfo();cp.FileName = Application.ExecutablePath;cp.Arguments = "cmd params";cp.UseShellExecute = true;Sy...

C#中,如何用代码分别实现系统注销,睡眠,休眠的功能?求高手解答!!
\/\/重启计算机代码 ProcessStartInfo ps = new ProcessStartInfo();ps.FileName = "shutdown.exe";ps.Arguments = "-r -t 0";Process.Start(ps);\/\/注销计算机代码 ProcessStartInfo ps = new ProcessStartInfo();ps.FileName = "shutdown.exe";ps.Arguments = "-l";Process.Start(ps);\/\/关闭...

c#如何实现关闭与重启计算机?
Process.Start(ps);这样就可以实现一次完整的关机了,重启,只需要改成ps.Arguments = "-r -t 1"即可;这个方法,主要是调用shutdown来执行的,比较简单,而且易学易用.方法2.调用系统API函数.操作系统关机,并不是依靠shutdown.exe来执行的,因为我们就算是把电脑上的shutdown.exe删除,机器一样可以正常关...

C# 远程机子重启
\/\/\/ 操作类型:ReStart 重启计算机 \/\/\/ Close关闭计算机 \/\/\/ ResetUser注销当前用户 \/\/\/ public enum OperatorType { ReStart=0,Close=1,ResetUser=2 } \/\/\/ \/\/\/ ComputerOperator 的摘要说明 \/\/\/ public class ComputerOperator { private string UserName;private string UserPassword;private...

C#调用API 关机,重起 怎么弄
二.使用C#调用cmd.exe执行shutdown.exe命令就行。Shutdown使您能够一次关闭或重新启动一台本地或远程计算机。语法shutdown [\/i | \/l | \/s | \/r | \/a | \/p | \/h | \/e] [\/f] [\/m \\\\ComputerName] [\/t XXX] [\/d [p:] XX:YY [\/c "Comment"]]参数\/i显示“远程关机对话框”...

用C#能让电脑定时关机的代码怎么写
-s -t 7200 (两个小时之后关机)at 12:00 shutdown -s (12:00关机)其他设置:shutdown.exe -a 取消关机 shutdown.exe -s 关机 shutdown.exe -f 强行关闭应用程序。shutdown.exe -m \\\\计算机名 控制远程计算机。 shutdown.exe -l 注销当前用户。shutdown.exe -r 关机并重启。

c#实现关机,注销,等等,查看user32.dll中的常数
ExitWindowsEx可以实现关机,注销,重启。第一个参数是关机类型:1:关机。2:重启。8:关机(和1稍微有点差别,但基本可以忽略)上面3个都要求SE_SHUTDOWN_NAME权限(你的应该就是没有权限关不了)。0:注销。另外还有4个值。0x400000:Win8中用的。0x40基本用不到吧。。0x4是可选的表示强制(但可能...

相似回答