SIGN UP MEMBER LOGIN:    
ARTICLE

Shut down, restart, log off and forced log off system using C#

Posted by Dhananjay Kumar Articles | Visual C# May 19, 2010
In this article we will see how to shut down, restart, log off and forced log off system using C#.
Reader Level:

Objective 

In this article, I am going to show, 
  1. How to Shut Down a machine 
  2. How to Log Off a machine
  3. How to forced log off a machine
  4. How to restart a machine using c# 
To perform our task, very first let us create a windows application project.   On form drag and drop four buttons for four different operations.  After design form will look like below 

1.gif 

Navigate to code behind of form and add reference of System.Runtime.InteropServices

Add a static extern method to Form.cs

[DllImport("user32.dll")]
public static extern int ExitWindowsEx(int operationFlag, int operationReason);

Log off  the System 

On click event of Log Off button, call ExitWindowsEX method with proper flag.  For log off  operation flag value is 0. 

private void btnLogOff_Click(object sender, EventArgs e)
{
    ExitWindowsEx(0, 0);
}

Forced Log off the System 

On click event of Forced Log Off button, call ExitWindowsEX method with proper flag.  For Forced  log off  operation flag value is 4. 

private void btnForcedLogOff_Click(object sender, EventArgs e)
{
   ExitWindowsEx(4, 0);
}

Shut Down the System

On click event of Shut down button, call ExitWindowsEX method with proper flag.  For shut down  operation flag value is 1. 

private void btnShutDown_Click(object sender, EventArgs e)
{
    ExitWindowsEx(1, 0);
}

Restart the System 

On click event of Restart button, call ExitWindowsEX method with proper flag.  For Restart  operation flag value is 2. 

private void btnRestart_Click(object sender, EventArgs e)
{
    ExitWindowsEx(2, 0);
}

Now when you run the application all system operation should be performed. 

For your reference full source code is given here 

Form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace SystmShutDownApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        [DllImport("user32.dll")]
        public static extern int ExitWindowsEx(int operationFlag, int operationReason);
        private void btnRestart_Click(object sender, EventArgs e)
        {
              ExitWindowsEx(2, 0);
        }
        private void btnLogOff_Click(object sender, EventArgs e)
        {
            ExitWindowsEx(0, 0);
        }
        private void btnForcedLogOff_Click(object sender, EventArgs e)
        {
           ExitWindowsEx(4, 0);
        }
        private void btnShutDown_Click(object sender, EventArgs e)
        {
            ExitWindowsEx(1, 0);
        }
    }
}

Thanks for reading. I hope post was useful. Happy Coding. 

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 

Hi Dhananjay Kumar,


Restart and Shutdown operations are not working.

Posted by Ravi Majji Jun 01, 2010

/*

hellow kumar

your program did not works but

i have finally improved part of it

*/

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace RestartShutDown

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

[StructLayout(LayoutKind.Sequential, Pack=1)]

internal struct TokPriv1Luid

{

public int Count;

public long Luid;

public int Attr;

}

[DllImport("kernel32.dll", ExactSpelling=true) ]

internal static extern IntPtr GetCurrentProcess();

[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]

internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr

phtok );

[DllImport("advapi32.dll", SetLastError=true) ]

internal static extern bool LookupPrivilegeValue( string host, string name,

ref long pluid );

[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]

internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall,

ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );

[DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ]

internal static extern bool ExitWindowsEx( int flg, int rea );

internal const int SE_PRIVILEGE_ENABLED = 0x00000002;

internal const int TOKEN_QUERY = 0x00000008;

internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;

internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";

internal const int EWX_LOGOFF = 0x00000000;

internal const int EWX_SHUTDOWN = 0x00000001;

internal const int EWX_REBOOT = 0x00000002;

internal const int EWX_FORCE = 0x00000004;

internal const int EWX_POWEROFF = 0x00000008;

internal const int EWX_FORCEIFHUNG = 0x00000010;

private void btnShutDown_Click(object sender, EventArgs e)

{

bool ok;

TokPriv1Luid tp;

IntPtr hproc = GetCurrentProcess();

IntPtr htok = IntPtr.Zero;

ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );

tp.Count = 1; tp.Luid = 0;

tp.Attr = SE_PRIVILEGE_ENABLED;

ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );

ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );

ok = ExitWindowsEx(EWX_SHUTDOWN, 0);

}

private void btnReboot_Click(object sender, EventArgs e)

{

bool ok;

TokPriv1Luid tp;

IntPtr hproc = GetCurrentProcess();

IntPtr htok = IntPtr.Zero;

ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);

tp.Count = 1; tp.Luid = 0;

tp.Attr = SE_PRIVILEGE_ENABLED;

ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);

ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);

ok = ExitWindowsEx(EWX_REBOOT, 0);

}

/* usage:

DoExitWin( EWX_SHUTDOWN );

or

DoExitWin( EWX_REBOOT );

*/

//------------------------

}

}

//------------------

//and this by system managment

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Runtime.InteropServices;

using System.Management;

namespace ShutDownRestart

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

}

private void ShutDownBntClick(object sender, EventArgs e)

{

ManagementBaseObject mboShutdown = null;

ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");

mcWin32.Get();

// You can't shutdown without security privileges

mcWin32.Scope.Options.EnablePrivileges = true;

ManagementBaseObject mboShutdownParams =mcWin32.GetMethodParameters("Win32Shutdown");

// Flag 1 means we want to shut down the system. Use "2" to reboot.

mboShutdownParams["Flags"] = "1";

mboShutdownParams["Reserved"] = "0";

foreach (ManagementObject manObj in mcWin32.GetInstances())

{

mboShutdown = manObj.InvokeMethod("Win32Shutdown",mboShutdownParams, null);

}

}

public enum ShutDown

{

LogOff = 0, Shutdown = 1, Reboot = 2, ForcedLogOff = 4, ForcedShutdown = 5,

ForcedReboot = 6, PowerOff = 8, ForcedPowerOff = 12

}

private void RebootClick(object sender, EventArgs e)

{

ManagementBaseObject inParams=null, outParams=null;

ManagementClass W32_OS = new ManagementClass("Win32_OperatingSystem");

int result;

W32_OS.Scope.Options.EnablePrivileges = true;

foreach (ManagementObject obj in W32_OS.GetInstances())

{

inParams=obj.GetMethodParameters("Win32Shutdown");

inParams["Flags"] = ShutDown.ForcedShutdown;//5

inParams["Reserved"]=0;

outParams = obj.InvokeMethod("Reboot", inParams, null);//("Win32Shutdown", inParams, null);

result = Convert.ToInt32(outParams["returnValue"]);

if (result != 0) throw new Win32Exception(result);

}

}

}

}

Posted by khalid sabtan May 31, 2010

Hi

  Great article but how to hibernate of the system using c#.

Posted by Vishal Tyagi May 19, 2010
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor