Vidya
Vidya

Reputation: 1

How does this work? It gives the answer but I don`t understand it.

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;
        ManagementBaseObject inParameter = sysOs.GetMethodParameters("Win32Shutdown");
        inParameter["Flags"] = "8";
        inParameter["Reserved"] = "0";
        foreach (ManagementObject maObj in sysOs.GetInstances())
        {
            outParameter = maObj.InvokeMethod("Win32Shutdown", inParameter, null);
        }
    }

Upvotes: 0

Views: 791

Answers (3)

JBRWilkinson
JBRWilkinson

Reputation: 4855

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

Upvotes: 0

James
James

Reputation: 82096

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

Upvotes: 2

Alex K.
Alex K.

Reputation: 175748

You are using .net managed objects to interact with the WMI subsystem of windows, specifically the Win32Shutdown method of the Win32_OperatingSystem Class.

Upvotes: 0

Related Questions