本文介绍了如何从 C# 关闭计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从 C# 程序关闭计算机的最佳方法是什么?
What's the best way to shut down the computer from a C# program?
我发现了一些有效的方法 - 我将在下面发布它们 - 但它们都不是很优雅.我正在寻找更简单的原生 .
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .
推荐答案摘自:Geekpedia 帖子
此方法使用 WMI 来关闭窗口.
This method uses WMI to shutdown windows.
您需要将 System.Management 的引用添加到您的项目中才能使用它.
You'll need to add a reference to System.Management to your project to use this.
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); } }更多推荐
如何从 C# 关闭计算机
发布评论