[英]How does this work? It gives the answer but I don`t understand it.
以下代码如何工作? 它给出了我想要的答案。 但是我想知道它是如何工作的?
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);
}
}
它使用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);
}
您正在使用.net托管对象与Windows的WMI子系统进行交互,特别是Win32_OperatingSystem
类的Win32Shutdown
方法。
如果您使用Win32 API'InitiateSystemShutdownEx ',将会更容易理解发生了什么。 这是C / C ++ API,因此您需要像这样将其“导入”到C#中: http : //www.pinvoke.net/default.aspx/advapi32/InitiateSystemShutdownEx.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.