以下代码如何运作?它给出了我想要的答案。但我想知道它是如何工作的?
public static void ShutDownComputer()
{
ManagementBaseObject outParameter = null;
ManagementClass sysOs = new ManagementClass("Win32_OperatingSystem");
sysOs.Get();
sysOs.Scope.Options.EnablePrivileges = true;
ManagementBaseObject inParameter = sysOs.GetMethodParameters("Win32Shutdown");
inParameter["Flags"] = "8";
inParameter["Reserved"] = "0";
foreach (ManagementObject maObj in sysOs.GetInstances())
{
outParameter = maObj.InvokeMethod("Win32Shutdown", inParameter, null);
}
}
答案 0 :(得分:2)
正在使用Windows Management Instrumentation (WMI)来调用Win32Shutdown方法。
// Creates a class which represents the model of the OS:
ManagementClass sysOs = new ManagementClass("Win32_OperatingSystem");
// Binds the class to the management object
sysOs.Get();
// Enables user priveledges for the connection, this is required to perform actions like shutdown
sysOs.Scope.Options.EnablePriviledges = true;
// Set the flag to indicate a "Power Off" (see the method link above for others)
inParameter["Flags"] = "8";
// According to MSDN the "Reserved" parameter is ignored hence its just being set to 0
inParameter["Reserved"] = "0";
// iteratve over all instances of the management object (which would be one in your case)
// and invoke the "Win32Shutdown" command using the parameters specified above.
foreach (ManagementObject maObj in sysOs.GetInstances())
{
outParameter = maObj.InvokeMethod("Win32Shutdown", inParameter, null);
}
答案 1 :(得分:0)
您正在使用.net托管对象与WMI subsystem of windows进行互动,特别是Win32_OperatingSystem
类的Win32Shutdown
方法。
答案 2 :(得分:0)
如果您使用Win32 API“InitiateSystemShutdownEx”,您将更容易理解正在发生的事情。这是一个C / C ++ API,因此您需要将其“导入”到C#中,如下所示:http://www.pinvoke.net/default.aspx/advapi32/InitiateSystemShutdownEx.html