Пример #1
0
        /// <summary>
        /// Initiates a shutdown and restart of the specified computer, and restarts any applications that have been registered for restart.
        /// </summary>
        /// <param name="machineName">The name of the computer to be shut down. If the value of this parameter is NULL, the local computer is shut down.</param>
        /// <param name="message">The message to be displayed in the interactive shutdown dialog box.</param>
        /// <param name="gracePeriod">The number of seconds to wait before shutting down the computer. If the value of this parameter is zero, the computer is shut down immediately. This value is limited to MAX_SHUTDOWN_TIMEOUT.
        /// <para>If the value of this parameter is greater than zero, and the dwShutdownFlags parameter specifies the flag SHUTDOWN_GRACE_OVERRIDE, the function fails and returns the error code ERROR_BAD_ARGUMENTS.</para></param>
        /// <param name="flags">One or more bit flags that specify options for the shutdown.</param>
        /// <param name="reason">The reason for initiating the shutdown. This parameter must be one of the system shutdown reason codes. If this parameter is zero, the default is an undefined shutdown that is logged as "No title for this reason could be found". By default, it is also an unplanned shutdown. Depending on how the system is configured, an unplanned shutdown triggers the creation of a file that contains the system state information, which can delay shutdown. Therefore, do not use zero for this parameter.</param>
        public static void InitiateShutdown(string machineName, string message, TimeSpan gracePeriod, ShutdownFlags flags, SystemShutDownReason reason = SystemShutDownReason.SHTDN_REASON_UNKNOWN)
        {
            var graceSecs = (uint)gracePeriod.TotalSeconds;

            if (graceSecs > MAX_SHUTDOWN_TIMEOUT)
            {
                throw new ArgumentOutOfRangeException(nameof(gracePeriod), $"Grace period can be no longer than {MAX_SHUTDOWN_TIMEOUT} seconds.");
            }
            using (string.IsNullOrEmpty(machineName) ? new PrivilegedCodeBlock(SystemPrivilege.Shutdown) : new PrivilegedCodeBlock(SystemPrivilege.RemoteShutdown))
                AdvApi32.InitiateShutdown(machineName, message, graceSecs, flags, reason);
        }