Monday, September 6, 2010

C# Tutorial: Create a Simple Shutdown Manager #2 [usingSystem.Management]

Here is the code

string flags, time, oldtime;
/////////////////////////////////////

///////// Button "Start" ////////////
time = textBox1.Text;
switch (comboBox1.SelectedIndex)
{
    case 0: { flags = "1"; toolStripStatusLabel1.Text = "Windows will shut down in " + time + " seconds!"; } break;
    case 1: { flags = "2"; toolStripStatusLabel1.Text = "Windows will restart in " + time + " seconds!"; } break;
    case 2: { flags = "0"; toolStripStatusLabel1.Text = "Windows will log off in " + time + " seconds!"; } break;
}
timer1.Start();

//////// Shutdown Function //////////
public void Shutdown()
{
    ManagementBaseObject shutdown = null;
    ManagementClass win32 = new ManagementClass("Win32_OperatingSystem");
    win32.Get();
    // You can't shutdown without security privileges 
    win32.Scope.Options.EnablePrivileges = true;
    // 1 - Shutdown; 2 - Restart; 0 - Log Off; 4 - Forced Log Off; 5 - Forced Shutdown; 6 - Forced Restart; 8 - Power Off; 12 - Forced Power Off.
    ManagementBaseObject shutdownparam = win32.GetMethodParameters("Win32Shutdown");
    shutdownparam["Flags"] = flags;
    shutdownparam["Reserved"] = "0";
    foreach (ManagementObject mObj in win32.GetInstances())
    {
        shutdown = mObj.InvokeMethod("Win32Shutdown", shutdownparam, null);  
    }
}

///////// Button "Abort" ////////////
timer1.Stop(); toolStripStatusLabel1.Text = "Task Aborted";


//////// Timer //////////////////////
oldtime = time;
time = (Convert.ToInt32(time) - 1).ToString();
toolStripStatusLabel1.Text = toolStripStatusLabel1.Text.Replace(oldtime, time);
if (time == "0") { Shutdown(); timer1.Stop(); }

Or download the solution

No comments:

Post a Comment