Shut down system using C#

Shut down system using C#
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.}
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top