【发布时间】:2009-03-20 08:55:29
【问题描述】:
如何使用 C# 关闭我的计算机?
【问题讨论】:
如何使用 C# 关闭我的计算机?
【问题讨论】:
一个简单的方法:使用 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 的 c# 包装类。
有时您需要重新启动或 关闭操作系统 您的应用程序(例如,在 程序的安装)。这 .NET 框架为您提供了一个间接的 重启电脑的方法 Windows 管理规范 System.Management 中的 (WMI) 类 命名空间,但是,似乎有 实施中的一些问题。
这就是我们创建 WindowsController 类 实现一些API函数 重新启动并关闭 Windows。它 支持所有 ExitWindowsEx 模式 它还可以休眠和挂起 系统。
这个类在 C# 和 VB.NET 版本。它可以编译为 .NET 模块或库 从其他 .NET 语言中使用。自从 它依赖于 Windows API,它将 不适用于 Linux 或 FreeBSD。
(mentalis.org)
【讨论】:
使用here 显示的“用户注销”代码的变体。
该代码使用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);
}
}
【讨论】: