如何使用 C# 关闭我的计算机?
7 回答
一个简单的方法:使用 Process.Start 运行 shutdown.exe。
shutdown /s /t 0
编程方式:P/Invoke 对ExitWindowsEx的调用
这将是 P/Invoke 签名:
[DllImport("aygshell.dll", SetLastError="true")]
private static extern bool ExitWindowsEx(uint dwFlags, uint dwReserved);
在任何情况下,运行代码的用户都需要关闭系统权限(通常不是问题,但需要记住的重要一点)。
不同的方法:
A. System.Diagnostics.Process.Start("关机", "-s -t 10");
B. Windows 管理规范 (WMI)
http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=36953
http://www.dreamincode.net/forums/showtopic33948.htm
C. System.Runtime.InteropServices Pinvoke
http://bytes.com/groups/net-c/251367-shutdown-my-computer-using-c
D. 系统管理
http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html
投稿后,看到好多人也发了。。。
WindowsController是 ExitWindowsEx 周围的 ac# 包装类。
有时您需要从应用程序中重新启动或关闭操作系统(例如,在安装程序之后)。.NET 框架为您提供了一种通过 System.Management 命名空间中的 Windows Management Instrumentation (WMI) 类重新启动计算机的间接方法,但是,它们的实现似乎存在一些问题。
这就是我们创建 WindowsController 类的原因,该类实现了一些 API 函数来重新启动和关闭 Windows。它支持所有 ExitWindowsEx 模式,还可以休眠和挂起系统。
此类在 C# 和 VB.NET 版本中可用。它可以编译为 .NET 模块或库,以便从其他 .NET 语言中使用。由于它依赖于 Windows API,因此无法在 Linux 或 FreeBSD 上运行。
(mentalis.org)
使用此处显示的“用户注销”代码的变体。
该代码使用ExitWindowsEx
API 调用。
猜测(未经测试):
Process.Start("shutdown", "-s -t 0");
艰难的方式,完美地在笔记本电脑上工作,虽然它需要一些时间:
Spawn a couple endless loops in more threads than cpu cores.
Wait for overheat which will automatically shutdown a computer.
:)
您也可以使用 InitiateSystemShutdown
http://www.pinvoke.net/default.aspx/advapi32.initiatesystemshutdown
using System;
using System.Runtime.InteropServices;
using System.Text;
public class Program
{
[DllImport( "advapi32.dll" ) ]
public static extern bool InitiateSystemShutdown( string MachineName , string Message , uint Timeout , bool AppsClosed , bool Restart );
[DllImport( "kernel32.dll" ) ]
public static extern uint GetLastError();
[DllImport( "kernel32.dll" ) ]
public static extern uint FormatMessage( uint Flags , IntPtr Source , uint MessageID , uint LanguageID , StringBuilder Buffer , uint Size , IntPtr Args );
public static void Main()
{
InitiateSystemShutdown(System.Environment.MachineName, "hello", 0, false, false);
//InitiateSystemShutdown("localhost", "hello", 0, false, false);
}
}