6

如何使用 C# 关闭我的计算机?

4

7 回答 7

10

一个简单的方法:使用 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);

在任何情况下,运行代码的用户都需要关闭系统权限(通常不是问题,但需要记住的重要一点)。

于 2009-03-20T08:59:39.027 回答
5

不同的方法:

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

投稿后,看到好多人也发了。。。

于 2009-03-20T09:15:50.220 回答
4

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)

于 2009-03-20T09:21:27.070 回答
1

使用此处显示的“用户注销”代码的变体。

该代码使用ExitWindowsExAPI 调用。

于 2009-03-20T09:03:44.680 回答
0

猜测(未经测试):

Process.Start("shutdown", "-s -t 0");
于 2009-03-20T09:00:12.253 回答
0

艰难的方式,完美地在笔记本电脑上工作,虽然它需要一些时间:

Spawn a couple endless loops in more threads than cpu cores.
Wait for overheat which will automatically shutdown a computer.

:)

于 2009-03-20T09:07:12.457 回答
0

您也可以使用 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);

    }
}
于 2015-11-04T12:22:02.993 回答