This code shut downs the operating system using the System.Management assembly, but not before obtaining the required security privileges.
1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Text;
7. using System.Windows.Forms;
8. // Remember to add a reference to the System.Management assembly
9. using System.Management;
10.
11. namespace ShutDown
12. {
13. public partial class Form1 : Form
14. {
15. public Form1()
16. {
17. InitializeComponent();
18. }
19.
20. private void btnShutDown_Click(object sender, EventArgs e)
21. {
22. ManagementBaseObject mboShutdown = null;
23. ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
24. mcWin32.Get();
25. // You can't shutdown without security privileges
26. mcWin32.Scope.Options.EnablePrivileges = true;
27. ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
28. // Flag 1 means we want to shut down the system
29. mboShutdownParams["Flags"] = "1";
30. mboShutdownParams["Reserved"] = "0";
31. foreach (ManagementObject manObj in mcWin32.GetInstances())
32. {
33. mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
34. }
35. }
36. }
37.}