How does the following code work? It gives the answer how I want. But I want to know how it works?
public static void ShutDownComputer()
{
ManagementBaseObject outParameter = null;
ManagementClass sysOs = new ManagementClass("Win32_OperatingSystem");
sysOs.Get();
sysOs.Scope.Options.EnablePrivileges = true;
Man开发者_运维知识库agementBaseObject inParameter = sysOs.GetMethodParameters("Win32Shutdown");
inParameter["Flags"] = "8";
inParameter["Reserved"] = "0";
foreach (ManagementObject maObj in sysOs.GetInstances())
{
outParameter = maObj.InvokeMethod("Win32Shutdown", inParameter, null);
}
}
It is using Windows Management Instrumentation (WMI) to invoke the Win32Shutdown method.
// 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);
}
You are using .net managed objects to interact with the WMI subsystem of windows, specifically the Win32Shutdown
method of the Win32_OperatingSystem
Class.
It would be much easier for you to understand what's going on if you use the Win32 API 'InitiateSystemShutdownEx'. This is a C/C++ API, so you need to 'import' it into C# like this: http://www.pinvoke.net/default.aspx/advapi32/InitiateSystemShutdownEx.html
精彩评论