Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Support Forum
Download Visual Studio Add-In

Terms of Use
Privacy Policy
InitiateSystemShutdown (advapi32)
 
.
Summary
Initiates a shutdown and optional restart of the specified computer, and optionally records the reason for the shutdown.
Summary
Initiate the system shutdown

C# Signature:

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool InitiateSystemShutdownEx(
    string lpMachineName,
    string lpMessage,
    uint dwTimeout,
    bool bForceAppsClosed,
    bool bRebootAfterShutdown,
    ShutdownReason dwReason);
[DllImport("advapi32.dll")]
static extern bool InitiateSystemShutdown(
            [MarshalAs(UnmanagedType.LPStr)] string lpMachinename,
            [MarshalAs(UnmanagedType.LPStr)] string lpMessage,
            Int32 dwTimeout,
            bool bForceAppsClosed,
            bool bRebootAfterShutdown);

VB Signature:

Declare Function InitiateSystemShutdown Lib "advapi32.dll" (TODO) As TODO

User-Defined Types:

None.

  [Flags]
  public enum ShutdownReason : uint
  {
    // Microsoft major reasons.
    SHTDN_REASON_MAJOR_OTHER        = 0x00000000,
    SHTDN_REASON_MAJOR_NONE         = 0x00000000,
    SHTDN_REASON_MAJOR_HARDWARE         = 0x00010000,
    SHTDN_REASON_MAJOR_OPERATINGSYSTEM      = 0x00020000,
    SHTDN_REASON_MAJOR_SOFTWARE         = 0x00030000,
    SHTDN_REASON_MAJOR_APPLICATION      = 0x00040000,
    SHTDN_REASON_MAJOR_SYSTEM           = 0x00050000,
    SHTDN_REASON_MAJOR_POWER        = 0x00060000,
    SHTDN_REASON_MAJOR_LEGACY_API       = 0x00070000,

Notes:

None.

    // Microsoft minor reasons.
    SHTDN_REASON_MINOR_OTHER        = 0x00000000,
    SHTDN_REASON_MINOR_NONE         = 0x000000ff,
    SHTDN_REASON_MINOR_MAINTENANCE      = 0x00000001,
    SHTDN_REASON_MINOR_INSTALLATION     = 0x00000002,
    SHTDN_REASON_MINOR_UPGRADE          = 0x00000003,
    SHTDN_REASON_MINOR_RECONFIG         = 0x00000004,
    SHTDN_REASON_MINOR_HUNG         = 0x00000005,
    SHTDN_REASON_MINOR_UNSTABLE         = 0x00000006,
    SHTDN_REASON_MINOR_DISK         = 0x00000007,
    SHTDN_REASON_MINOR_PROCESSOR        = 0x00000008,
    SHTDN_REASON_MINOR_NETWORKCARD      = 0x00000000,
    SHTDN_REASON_MINOR_POWER_SUPPLY     = 0x0000000a,
    SHTDN_REASON_MINOR_CORDUNPLUGGED    = 0x0000000b,
    SHTDN_REASON_MINOR_ENVIRONMENT      = 0x0000000c,
    SHTDN_REASON_MINOR_HARDWARE_DRIVER      = 0x0000000d,
    SHTDN_REASON_MINOR_OTHERDRIVER      = 0x0000000e,
    SHTDN_REASON_MINOR_BLUESCREEN       = 0x0000000F,
    SHTDN_REASON_MINOR_SERVICEPACK      = 0x00000010,
    SHTDN_REASON_MINOR_HOTFIX           = 0x00000011,
    SHTDN_REASON_MINOR_SECURITYFIX      = 0x00000012,
    SHTDN_REASON_MINOR_SECURITY         = 0x00000013,
    SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY = 0x00000014,
    SHTDN_REASON_MINOR_WMI          = 0x00000015,
    SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL = 0x00000016,
    SHTDN_REASON_MINOR_HOTFIX_UNINSTALL     = 0x00000017,
    SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL = 0x00000018,
    SHTDN_REASON_MINOR_MMC          = 0x00000019,
    SHTDN_REASON_MINOR_TERMSRV          = 0x00000020,

Tips & Tricks:

Please add some!

    // Flags that end up in the event log code.
    SHTDN_REASON_FLAG_USER_DEFINED      = 0x40000000,
    SHTDN_REASON_FLAG_PLANNED           = 0x80000000,
    SHTDN_REASON_UNKNOWN            = SHTDN_REASON_MINOR_NONE,
    SHTDN_REASON_LEGACY_API         = (SHTDN_REASON_MAJOR_LEGACY_API | SHTDN_REASON_FLAG_PLANNED),

C# sample code: sivakumar.keerthi

***

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Text;

using System.Runtime.InteropServices;

    // This mask cuts out UI flags.
    SHTDN_REASON_VALID_BIT_MASK         = 0xc0ffffff
  }

namespace ShutDown

{

    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class FrmMain : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button CmdExit;
        private System.Windows.Forms.Label LblTimeout;
        private System.Windows.Forms.NumericUpDown NumTimeOut;
        private System.Windows.Forms.CheckBox chkReboot;
        private System.Windows.Forms.Button CmdShutDown;
        [ DllImport( "advapi32.dll" ) ]
        public static extern bool InitiateSystemShutdown( string MachineName , string Message , uint Timeout , bool AppsClosed , bool Restart );
        [ DllImport( "kernel32.dll" ) ]
        public static extern uint GetLastError();
        [ DllImport( "kernel32.dll" ) ]
        public static extern uint FormatMessage( uint Flags , IntPtr Source , uint MessageID , uint LanguageID , StringBuilder Buffer , uint Size , IntPtr Args );
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

VB.NET Signature:

<DllImport("advapi32.dll", SetLastError:=True)> _
Public Function InitiateSystemShutdownEx( _
     ByVal lpMachineName As String, _
     ByVal lpMessage As String, _
     ByVal Timeout As UInteger, _
     <MarshalAs(UnmanagedType.Bool)> ByVal bForceAppsClosed As Boolean, _
     <MarshalAs(UnmanagedType.Bool)> ByVal bRebootAfterShutdown As Boolean, _
     ByVal ShutdownReason As ShutdownReason) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function
        public FrmMain()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            Image Img = Image.FromFile( Application.StartupPath + "\\" + "ShutDown.gif" );
            CmdShutDown.Image = Img;
            this.ShowInTaskbar = false;
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

  <Flags()> _
    Public Enum ShutdownReason As UInteger
    ' Microsoft major reasons.
    SHTDN_REASON_MAJOR_OTHER = &H0UI
    SHTDN_REASON_MAJOR_NONE = &H0UI
    SHTDN_REASON_MAJOR_HARDWARE = &H10000UI
    SHTDN_REASON_MAJOR_OPERATINGSYSTEM = &H20000UI
    SHTDN_REASON_MAJOR_SOFTWARE = &H30000UI
    SHTDN_REASON_MAJOR_APPLICATION = &H40000UI
    SHTDN_REASON_MAJOR_SYSTEM = &H50000UI
    SHTDN_REASON_MAJOR_POWER = &H60000UI
    SHTDN_REASON_MAJOR_LEGACY_API = &H70000UI
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

    ' Microsoft minor reasons.
    SHTDN_REASON_MINOR_OTHER = &H0UI
    SHTDN_REASON_MINOR_NONE = &HFFUI
    SHTDN_REASON_MINOR_MAINTENANCE = &H1UI
    SHTDN_REASON_MINOR_INSTALLATION = &H2UI
    SHTDN_REASON_MINOR_UPGRADE = &H3UI
    SHTDN_REASON_MINOR_RECONFIG = &H4UI
    SHTDN_REASON_MINOR_HUNG = &H5UI
    SHTDN_REASON_MINOR_UNSTABLE = &H6UI
    SHTDN_REASON_MINOR_DISK = &H7UI
    SHTDN_REASON_MINOR_PROCESSOR = &H8UI
    SHTDN_REASON_MINOR_NETWORKCARD = &H0UI
    SHTDN_REASON_MINOR_POWER_SUPPLY = &HAUI
    SHTDN_REASON_MINOR_CORDUNPLUGGED = &HBUI
    SHTDN_REASON_MINOR_ENVIRONMENT = &HCUI
    SHTDN_REASON_MINOR_HARDWARE_DRIVER = &HDUI
    SHTDN_REASON_MINOR_OTHERDRIVER = &HEUI
    SHTDN_REASON_MINOR_BLUESCREEN = &HFUI
    SHTDN_REASON_MINOR_SERVICEPACK = &H10UI
    SHTDN_REASON_MINOR_HOTFIX = &H11UI
    SHTDN_REASON_MINOR_SECURITYFIX = &H12UI
    SHTDN_REASON_MINOR_SECURITY = &H13UI
    SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY = &H14UI
    SHTDN_REASON_MINOR_WMI = &H15UI
    SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL = &H16UI
    SHTDN_REASON_MINOR_HOTFIX_UNINSTALL = &H17UI
    SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL = &H18UI
    SHTDN_REASON_MINOR_MMC = &H19UI
    SHTDN_REASON_MINOR_TERMSRV = &H20UI
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.CmdExit = new System.Windows.Forms.Button();
            this.LblTimeout = new System.Windows.Forms.Label();
            this.NumTimeOut = new System.Windows.Forms.NumericUpDown();
            this.chkReboot = new System.Windows.Forms.CheckBox();
            this.CmdShutDown = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.NumTimeOut)).BeginInit();
            this.SuspendLayout();
            //
            // CmdExit
            //
            this.CmdExit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.CmdExit.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.CmdExit.ForeColor = System.Drawing.Color.Red;
            this.CmdExit.Location = new System.Drawing.Point(287, 178);
            this.CmdExit.Name = "CmdExit";
            this.CmdExit.TabIndex = 0;
            this.CmdExit.Text = "Exit";
            this.CmdExit.Click += new System.EventHandler(this.CmdExit_Click);
            //
            // LblTimeout
            //
            this.LblTimeout.AutoSize = true;
            this.LblTimeout.BackColor = System.Drawing.Color.Black;
            this.LblTimeout.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.LblTimeout.ForeColor = System.Drawing.Color.White;
            this.LblTimeout.Location = new System.Drawing.Point(6, 180);
            this.LblTimeout.Name = "LblTimeout";
            this.LblTimeout.Size = new System.Drawing.Size(64, 17);
            this.LblTimeout.TabIndex = 1;
            this.LblTimeout.Text = "Time out";
            this.LblTimeout.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // NumTimeOut
            //
            this.NumTimeOut.Location = new System.Drawing.Point(77, 180);
            this.NumTimeOut.Maximum = new System.Decimal(new int[] {
                                                                       600,
                                                                       0,
                                                                       0,
                                                                       0});
            this.NumTimeOut.Name = "NumTimeOut";
            this.NumTimeOut.Size = new System.Drawing.Size(56, 21);
            this.NumTimeOut.TabIndex = 2;
            //
            // chkReboot
            //
            this.chkReboot.ForeColor = System.Drawing.Color.White;
            this.chkReboot.Location = new System.Drawing.Point(278, 144);
            this.chkReboot.Name = "chkReboot";
            this.chkReboot.Size = new System.Drawing.Size(80, 24);
            this.chkReboot.TabIndex = 3;
            this.chkReboot.Text = "Restart";
            this.chkReboot.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.chkReboot.CheckedChanged += new System.EventHandler(this.chkReboot_CheckedChanged);
            //
            // CmdShutDown
            //
            this.CmdShutDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.CmdShutDown.ForeColor = System.Drawing.Color.White;
            this.CmdShutDown.Location = new System.Drawing.Point(136, 48);
            this.CmdShutDown.Name = "CmdShutDown";
            this.CmdShutDown.Size = new System.Drawing.Size(100, 80);
            this.CmdShutDown.TabIndex = 4;
            this.CmdShutDown.Text = "ShutDown";
            this.CmdShutDown.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            this.CmdShutDown.Click += new System.EventHandler(this.CmdShutDown_Click);
            //
            // FrmMain
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(8, 14);
            this.BackColor = System.Drawing.Color.Black;
            this.ClientSize = new System.Drawing.Size(368, 208);
            this.Controls.Add(this.CmdShutDown);
            this.Controls.Add(this.chkReboot);
            this.Controls.Add(this.NumTimeOut);
            this.Controls.Add(this.LblTimeout);
            this.Controls.Add(this.CmdExit);
            this.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "FrmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            ((System.ComponentModel.ISupportInitialize)(this.NumTimeOut)).EndInit();
            this.ResumeLayout(false);

    ' Flags that end up in the event log code.
    SHTDN_REASON_FLAG_USER_DEFINED = &H40000000UI
    SHTDN_REASON_FLAG_PLANNED = &H80000000UI
    SHTDN_REASON_UNKNOWN = SHTDN_REASON_MINOR_NONE
    SHTDN_REASON_LEGACY_API = (SHTDN_REASON_MAJOR_LEGACY_API Or SHTDN_REASON_FLAG_PLANNED)
        }
        #endregion

    ' This mask cuts out UI flags.
    SHTDN_REASON_VALID_BIT_MASK = &HC0FFFFFFUI
    End Enum

User-Defined Types:

None.

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new FrmMain());
        }

Notes:

lpMachineName: The network name of the computer to be shut down. If lpMachineName is NULL or an empty string, the function shuts down the local computer.

dwReason: The ShutdownReason enum can be used for this parameter.

        private void CmdExit_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }

Tips & Tricks:

None

        private void chkReboot_CheckedChanged(object sender, System.EventArgs e)
        {
            if ( chkReboot.Checked )
                NumTimeOut.Enabled = false;
            else
                NumTimeOut.Enabled = true;
        }

Sample Code:

None

        private void CmdShutDown_Click(object sender, System.EventArgs e)
        {
            try
            {
                string MachineName = Environment.MachineName;
                uint TimeOut = 0;
                string Message = string.Empty;
                if ( chkReboot.Checked )
                    TimeOut = 0;
                else
                {
                    TimeOut = uint.Parse( NumTimeOut.Value.ToString() );
                    Message = "Your system will shutdown in " + TimeOut.ToString() + " seconds";
                }
                bool AppsClosed = false;
                bool Restart = chkReboot.Checked;
                StringBuilder Buffer = new StringBuilder( 512 );
                uint MessageLength = 0;
                GetLastError();
                if ( !InitiateSystemShutdown( MachineName , Message , TimeOut , AppsClosed , Restart ) )
                {
                    MessageLength = FormatMessage( 0x00001000 , IntPtr.Zero , GetLastError() , 0 , Buffer , ( uint )Buffer.Capacity , IntPtr.Zero );
                    if( MessageLength > 0 )
                    {
                        string Error = Buffer.ToString();
                        Error = Error.Substring( 0 , Error.Length - 2 );
                        MessageBox.Show( Error + " (" + GetLastError().ToString() + ")" );
                    }
                }
            }
            catch( Exception ex )
            {
                MessageBox.Show( ex.Message );
            }
        }
    }

}

***

Alternative Managed API:

None

Documentation

Alternative Managed API:

    Public ErrMsg As String
    Private Flag As Integer = 8

    Function ShutdownPC(ByVal PC_Name As String, ByVal forced As Boolean) As Boolean
    Dim wmi As ManagementClass
    Dim objs As ManagementObjectCollection
    Dim obj As ManagementObject
    Dim Result As Integer

    If forced = True Then
        Flag += 4
    End If
    Try
        wmi = New ManagementClass("\\" & PC_Name & "\root\cimv2:Win32_OperatingSystem")
        objs = wmi.GetInstances()
        For Each obj In objs
        ' Get an input parameters object for this method
        Dim inParams As ManagementBaseObject = obj.GetMethodParameters("Win32Shutdown")
        ' fill 'em in
        inParams("Flags") = Flag
        inParams("Reserved") = 0
        ' do it!
        Dim outParams As ManagementBaseObject = obj.InvokeMethod("Win32Shutdown", inParams, Nothing)
        Result = Convert.ToInt32(outParams("returnValue"))
        If Result <> 0 Then
            ErrMsg = ErrorToString(Result)
            Return False
        End If
        Exit For
        Next
    Catch ex As Exception
        ErrMsg = ex.Message
        Return False
    End Try

    Return True
    End Function

Documentation

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions