如何从 C # 关闭计算机

从 C # 程序中关闭计算机的最好方法是什么?

我已经找到了一些有效的方法——我将在下面发布它们——但它们都不是很优雅。我要找的是更简单,更原生态的东西。网。

258550 次浏览

你可以启动关闭程序:

  • 关闭
  • 重新启动

摘自: 一篇 Geekpedia 的文章

此方法使用 WMI关闭窗口。

您需要在项目中添加对 System.Management 的引用才能使用此。

using System.Management;


void Shutdown()
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
mcWin32.Get();


// You can't shutdown without security privileges
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams =
mcWin32.GetMethodParameters("Win32Shutdown");


// Flag 1 means we want to shut down the system. Use "2" to reboot.
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown",
mboShutdownParams, null);
}
}

简短明了,打电话给外部程序:

    using System.Diagnostics;


void Shutdown()
{
Process.Start("shutdown.exe", "-s -t 00");
}

注意: 这会调用 Windows 的 Shutdown.exe 程序,所以它只有在该程序可用时才会工作。 您可能在 Windows 2000(其中 shutdown.exe 仅在资源工具包中可用)或 XP 嵌入式上遇到问题。

这个线程提供了必要的代码: http://bytes.com/forum/thread251367.html

但这是相关代码:

using System.Runtime.InteropServices;


[StructLayout(LayoutKind.Sequential, Pack=1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}


[DllImport("kernel32.dll", ExactSpelling=true) ]
internal static extern IntPtr GetCurrentProcess();


[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr
phtok );


[DllImport("advapi32.dll", SetLastError=true) ]
internal static extern bool LookupPrivilegeValue( string host, string name,
ref long pluid );


[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );


[DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool ExitWindowsEx( int flg, int rea );


internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;


private void DoExitWin( int flg )
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );
ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );
ok = ExitWindowsEx( flg, 0 );
}

用法:

DoExitWin( EWX_SHUTDOWN );

或者

DoExitWin( EWX_REBOOT );

没有。关闭计算机的网络本机方法。您需要 P/调用 ExitWindows 或 ExitWindowsEx API 调用。

老派的丑陋方法。使用来自 Win32API 的 ExitWindowsEx函数。

using System.Runtime.InteropServices;


void Shutdown2()
{
const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
const short SE_PRIVILEGE_ENABLED = 2;
const uint EWX_SHUTDOWN = 1;
const short TOKEN_ADJUST_PRIVILEGES = 32;
const short TOKEN_QUERY = 8;
IntPtr hToken;
TOKEN_PRIVILEGES tkp;


// Get shutdown privileges...
OpenProcessToken(Process.GetCurrentProcess().Handle,
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken);
tkp.PrivilegeCount = 1;
tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
LookupPrivilegeValue("", SE_SHUTDOWN_NAME, out tkp.Privileges.pLuid);
AdjustTokenPrivileges(hToken, false, ref tkp, 0U, IntPtr.Zero,
IntPtr.Zero);


// Now we have the privileges, shutdown Windows
ExitWindowsEx(EWX_SHUTDOWN, 0);
}


// Structures needed for the API calls
private struct LUID
{
public int LowPart;
public int HighPart;
}
private struct LUID_AND_ATTRIBUTES
{
public LUID pLuid;
public int Attributes;
}
private struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
public LUID_AND_ATTRIBUTES Privileges;
}


[DllImport("advapi32.dll")]
static extern int OpenProcessToken(IntPtr ProcessHandle,
int DesiredAccess, out IntPtr TokenHandle);


[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
[MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState,
UInt32 BufferLength,
IntPtr PreviousState,
IntPtr ReturnLength);


[DllImport("advapi32.dll")]
static extern int LookupPrivilegeValue(string lpSystemName,
string lpName, out LUID lpLuid);


[DllImport("user32.dll", SetLastError = true)]
static extern int ExitWindowsEx(uint uFlags, uint dwReason);

在生产代码中,您应该检查 API 调用的返回值,但为了使示例更清晰,我省略了这一点。

从 WindowsXP 开始工作,在 win2000或更低版本中不可用:

这是最快的方法:

Process.Start("shutdown","/s /t 0");

否则像其他人说的那样使用 P/Invoke 或 WMI。

编辑: 如何避免创建窗口

var psi = new ProcessStartInfo("shutdown","/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);

不同的方法:

答: System.Diagnostics.Process.Start("Shutdown", "-s -t 10");

Windows 管理规范

系统。运行时。 InteropServices 调用

系统管理

在我提交之后,我看到很多其他人也发布了..。

如果你想远程关闭计算机,然后你可以使用

Using System.Diagnostics;

点击任何按钮

{
Process.Start("Shutdown","-i");
}

我尝试用 Roomaroo 的 WMI 方法关闭 Windows 2003 Server,但是直到我在 Main ()声明中添加了‘[ STAThread ]’(即“ 单线公寓”线程模型) ,它才能工作:

[STAThread]
public static void Main(string[] args) {
Shutdown();
}

然后,我试图从一个线程关闭,为了让它工作,我必须将线程的“公寓状态”设置为 STA:

using System.Management;
using System.Threading;


public static class Program {


[STAThread]
public static void Main(string[] args) {
Thread t = new Thread(new ThreadStart(Program.Shutdown));
t.SetApartmentState(ApartmentState.STA);
t.Start();
...
}


public static void Shutdown() {
// roomaroo's code
}
}

我是一个 C # 菜鸟,所以我不能完全确定 STA 线程在关闭系统方面的重要性(即使在阅读了我上面发布的链接之后)。也许其他人可以详细说明... ?

请注意,shutdown.exe只是 InitiateSystemShutdownEx的一个包装器,它提供了 ExitWindowsEx中缺少的一些细节

精心设计的答案。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
// Remember to add a reference to the System.Management assembly
using System.Management;
using System.Diagnostics;


namespace ShutDown
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


private void btnShutDown_Click(object sender, EventArgs e)
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
mcWin32.Get();


// You can't shutdown without security privileges
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");


// Flag 1 means we want to shut down the system
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";


foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
}
}
}
}

我在尝试使用上面接受的 WMI 方法时遇到了麻烦,因为尽管我以管理员的身份运行这个程序,但是我总是有特权而没有异常。

解决方案是进程为自己请求特权。我在 http://www.dotnet247.com/247reference/msgs/58/292150.aspx找到了答案是一个叫 Richard Hill 的人写的。

我已经粘贴了我的基本使用他的解决方案下面的情况下,链接变老。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Runtime.InteropServices;
using System.Security;
using System.Diagnostics;


namespace PowerControl
{
public class PowerControl_Main
{




public void Shutdown()
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
mcWin32.Get();


if (!TokenAdjuster.EnablePrivilege("SeShutdownPrivilege", true))
{
Console.WriteLine("Could not enable SeShutdownPrivilege");
}
else
{
Console.WriteLine("Enabled SeShutdownPrivilege");
}


// You can't shutdown without security privileges
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");


// Flag 1 means we want to shut down the system
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";


foreach (ManagementObject manObj in mcWin32.GetInstances())
{
try
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown",
mboShutdownParams, null);
}
catch (ManagementException mex)
{
Console.WriteLine(mex.ToString());
Console.ReadKey();
}
}
}




}




public sealed class TokenAdjuster
{
// PInvoke stuff required to set/enable security privileges
[DllImport("advapi32", SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int OpenProcessToken(
System.IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);


[DllImport("kernel32", SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool CloseHandle(IntPtr handle);


[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int AdjustTokenPrivileges(
IntPtr TokenHandle,
int DisableAllPrivileges,
IntPtr NewState,
int BufferLength,
IntPtr PreviousState,
ref int ReturnLength);


[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool LookupPrivilegeValue(
string lpSystemName,
string lpName,
ref LUID lpLuid);


[StructLayout(LayoutKind.Sequential)]
internal struct LUID
{
internal int LowPart;
internal int HighPart;
}


[StructLayout(LayoutKind.Sequential)]
struct LUID_AND_ATTRIBUTES
{
LUID Luid;
int Attributes;
}


[StructLayout(LayoutKind.Sequential)]
struct _PRIVILEGE_SET
{
int PrivilegeCount;
int Control;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] // ANYSIZE_ARRAY = 1
LUID_AND_ATTRIBUTES[] Privileges;
}


[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_PRIVILEGES
{
internal int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
internal int[] Privileges;
}
const int SE_PRIVILEGE_ENABLED = 0x00000002;
const int TOKEN_ADJUST_PRIVILEGES = 0X00000020;
const int TOKEN_QUERY = 0X00000008;
const int TOKEN_ALL_ACCESS = 0X001f01ff;
const int PROCESS_QUERY_INFORMATION = 0X00000400;


public static bool EnablePrivilege(string lpszPrivilege, bool
bEnablePrivilege)
{
bool retval = false;
int ltkpOld = 0;
IntPtr hToken = IntPtr.Zero;
TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
tkp.Privileges = new int[3];
TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();
tkpOld.Privileges = new int[3];
LUID tLUID = new LUID();
tkp.PrivilegeCount = 1;
if (bEnablePrivilege)
tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
else
tkp.Privileges[2] = 0;
if (LookupPrivilegeValue(null, lpszPrivilege, ref tLUID))
{
Process proc = Process.GetCurrentProcess();
if (proc.Handle != IntPtr.Zero)
{
if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
ref hToken) != 0)
{
tkp.PrivilegeCount = 1;
tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
tkp.Privileges[1] = tLUID.HighPart;
tkp.Privileges[0] = tLUID.LowPart;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal(bufLength);
Marshal.StructureToPtr(tkp, tu, true);
if (AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref ltkpOld) != 0)
{
// successful AdjustTokenPrivileges doesn't mean privilege could be changed
if (Marshal.GetLastWin32Error() == 0)
{
retval = true; // Token changed
}
}
TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tu,
typeof(TOKEN_PRIVILEGES));
Marshal.FreeHGlobal(tu);
}
}
}
if (hToken != IntPtr.Zero)
{
CloseHandle(hToken);
}
return retval;
}


}
}
System.Diagnostics.Process.Start("shutdown", "/s /t 0")

应该可以。

对于重新启动,它是/r

这将重新启动电脑框直接和干净,没有对话框。

为了避免传递参数的问题,复杂的执行,从 Windows 窗体执行使用 PowerShell 执行脚本:

using System.Management.Automation;
...
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("shutdown -a; shutdown -r -t 100;");
// invoke execution on the pipeline (collecting output)
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
}

应该在 OS 上安装 System.Management.Automation.dll,并在 GAC 中可用。

对不起,我的英语不好。

为了补充一下 Pop Catalin 的回答,这里有一个 一个班轮,它可以关闭计算机而不显示任何窗口:

Process.Start(new ProcessStartInfo("shutdown", "/s /t 0") {
CreateNoWindow = true, UseShellExecute = false
});

对于 Windows 10,我需要添加/f 选项,以便关闭电脑没有任何问题和等待时间。

//This did not work for me
Process.Start("shutdown", "/s /t 0");


//But this worked
Process.Start("shutdown", "/s /f /t 0");