2010-05-11 76 views
0

下面的代碼是如何工作的?它給出了我想要的答案。但我想知道它是如何工作的?這是如何工作的?它給出了答案,但我不理解它。

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); 
     } 
    } 

回答

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);    
} 
相關問題