/// <summary>Initiates a shutdown and optional restart of the specified computer.</summary> /// <param name="machineName"> /// String that specifies the network name of the computer to shut down. If NULL or an empty string, the function shuts down the local computer. /// </param> /// <param name="message">String that specifies a message to display in the shutdown dialog box. This parameter can be NULL if no message is required.</param> /// <param name="timeout"> /// Time that the shutdown dialog box should be displayed, in seconds. While this dialog box is displayed, shutdown can be stopped by the /// AbortSystemShutdown function. /// </param> /// <param name="forceAppsClosed"> /// If this parameter is TRUE, applications with unsaved changes are to be forcibly closed. If this parameter is FALSE, the system displays a dialog box /// instructing the user to close the applications. /// </param> /// <param name="rebootAfterShutdown"> /// If this parameter is TRUE, the computer is to restart immediately after shutting down. If this parameter is FALSE, the system flushes all caches to /// disk and clears the screen. /// </param> /// <param name="reason">Reason for initiating the shutdown. This parameter must be one of the system shutdown reason codes.</param> /// <returns>0 on failure, non-zero for success</returns> public static bool InitiateShutdown(string machineName = null, string message = null, TimeSpan?timeout = null, bool forceAppsClosed = false, bool rebootAfterShutdown = false, AdvApi32.SystemShutDownReason reason = AdvApi32.SystemShutDownReason.SHTDN_REASON_UNKNOWN) { var graceSecs = (uint)timeout.GetValueOrDefault().TotalSeconds; if (Environment.OSVersion.Version.Major <= 5 && graceSecs > AdvApi32.MAX_SHUTDOWN_TIMEOUT) { throw new ArgumentOutOfRangeException(nameof(timeout), $"Timeout can be no longer than {AdvApi32.MAX_SHUTDOWN_TIMEOUT} seconds on Windows XP and earlier systems."); } using (string.IsNullOrEmpty(machineName) ? new PrivilegedCodeBlock(SystemPrivilege.Shutdown) : new PrivilegedCodeBlock(SystemPrivilege.RemoteShutdown)) return(AdvApi32.InitiateSystemShutdownEx(machineName, message, graceSecs, forceAppsClosed, rebootAfterShutdown, reason)); }
public static void Reboot() { Trace.WriteLine("OK - shutting down"); AcquireSystemPrivilege(AdvApi32.SE_SHUTDOWN_NAME); if (WinVersion.GetMajorVersion() >= 5 && WinVersion.GetMajorVersion() < 6) { User32.ExitWindowsEx( User32.ExitFlags.EWX_REBOOT | User32.ExitFlags.EWX_FORCE, 0 ); } else { AdvApi32.InitiateSystemShutdownEx( "", "", 0, true, true, AdvApi32.ShtdnReason.MAJOR_OTHER | AdvApi32.ShtdnReason.MINOR_ENVIRONMENT | AdvApi32.ShtdnReason.FLAG_PLANNED ); } }