Skip to content

How to shutdown the system Programatically?URGENT!!!

Krishna Kishore

Asked May 21, 2006, 9:17 PM EDT1 answer
Share
LinkedInX
Hai Friends,

How to shut down the system programatically using C#?
iam using ExitWindowsEx of VC++ function(by Interop Services)....
But I need a pure c# function......
Please help me in this issue...itz a bit urgent!!!!

Thanx.

regards,

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    You can do this by using namespace System.Management.ManagementClass and System.Management.ManagementBaseObject. Here is a sample code for this. //first include namespace System.Management using System.Management; // Then declare enum public enum ShutDown { LogOff = 0, Shutdown = 1, Reboot = 2, ForcedLogOff = 4, ForcedShutdown = 5, ForcedReboot = 6, PowerOff = 8, ForcedPowerOff = 12 } // then insert below mentioned code on button click event of any button private void button1_Click(object sender, System.EventArgs e) { DialogResult res = MessageBox.Show(this,"Are you sure you want to shutdown your machine?","Confirmation",MessageBoxButtons.OKCancel,MessageBoxIcon.Question); if(res == DialogResult.OK) { ManagementClass W32_OS = new ManagementClass("Win32_OperatingSystem"); ManagementBaseObject inParams, outParams; int result; W32_OS.Scope.Options.EnablePrivileges = true; foreach(ManagementObject obj in W32_OS.GetInstances()) { inParams = obj.GetMethodParameters("Win32Shutdown"); //inParams["Flags"] = ShutDown.ForcedShutdown; // ForcedShutdown; inParams["Flags"] = ShutDown.Shutdown ; inParams["Reserved"] = 0; outParams = obj.InvokeMethod("Win32Shutdown", inParams, null); result = Convert.ToInt32(outParams["returnValue"]); if (result !=0) throw new Win32Exception(result); } } else { return; } }
    0