Esempio n. 1
0
        public static void Exit(ShutdownFlags Flags = ShutdownFlags.Shutdown, int Reason = 0)
        {
            var    tp = new TokPriv1Luid(1, 0, AdvApi32.SE_PRIVILEGE_ENABLED);
            IntPtr hproc = Kernel32.CurrentProcess, htok = IntPtr.Zero;

            AdvApi32.OpenProcessToken(hproc, AdvApi32.TOKEN_ADJUST_PRIVILEGES | AdvApi32.TOKEN_QUERY, ref htok);
            AdvApi32.LookupPrivilegeValue(null, "SeShutdownPrivilege", ref tp.Luid);
            AdvApi32.AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);

            User32.ExitWindows(Flags, 0);
        }
Esempio n. 2
0
        public static void Exit(ShutdownFlags Flags = ShutdownFlags.Shutdown, int Reason = 0)
        {
            var tp = new TokPriv1Luid(1, 0, AdvApi32.SE_PRIVILEGE_ENABLED);
            IntPtr hproc = Kernel32.CurrentProcess, htok = IntPtr.Zero;

            AdvApi32.OpenProcessToken(hproc, AdvApi32.TOKEN_ADJUST_PRIVILEGES | AdvApi32.TOKEN_QUERY, ref htok);
            AdvApi32.LookupPrivilegeValue(null, "SeShutdownPrivilege", ref tp.Luid);
            AdvApi32.AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);

            User32.ExitWindows(Flags, 0);
        }
Esempio n. 3
0
 private static extern bool ExitWindowsEx(ShutdownFlags flags, int reason);
Esempio n. 4
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);
        }
Esempio n. 5
0
 public static extern Win32Error InitiateShutdown(string lpMachineName, string lpMessage, uint dwGracePeriod, ShutdownFlags dwShutdownFlags, SystemShutDownReason dwReason);
Esempio n. 6
0
 public static extern bool ExitWindows(ShutdownFlags Flag, int Reason);
Esempio n. 7
0
 public static extern UInt32 InitiateShutdown(
     string lpMachineName,          //The name of the computer to be shut down. If the value of this parameter is NULL, the local computer is shut down.
     string lpMessage,              //The message to be displayed in the interactive shutdown dialog box.
     UInt32 dwGracePeriod,          //The number of seconds to wait before shutting down the computer.
     ShutdownFlags dwShutdownFlags, //One or more bit flags that specify options for the shutdown.
     ShutdownReasons dwReason);     //The reason for initiating the shutdown.
Esempio n. 8
0
 internal static extern int InitiateShutdown([MarshalAs(UnmanagedType.LPWStr)] string lpMachineName, // null for localhost
                                             [MarshalAs(UnmanagedType.LPWStr)] string lpMessage,
                                             uint dwGracePeriod,                                     // seconds
                                             ShutdownFlags dwShutdownFlags,
                                             uint dwReason);
Esempio n. 9
0
 internal static extern bool ExitWindowsEx(ShutdownFlags uFlags, ShutdownReasons dwReason);
Esempio n. 10
0
        public static void ShutdownLegacy(string host, ShutdownFlags flags, string userid = "", string password = "", string message = "WARNINIGGG" +
                                          "This PC will Shutdown soon")
        {
            long          dwDelay          = default(long);
            StringBuilder shutdownCommand  = new StringBuilder("/c ");
            StringBuilder shutdownCommand1 = new StringBuilder(" /c ");
            Process       p     = new Process();
            Process       p1    = new Process();
            string        error = string.Empty;

            try
            {
                dwDelay = 20;

                if ((string.IsNullOrEmpty(host)))
                {
                    return;
                }

                if ((!string.IsNullOrEmpty(userid)))
                {
                    shutdownCommand.AppendFormat(@"net use \\{0}\IPC$ ""{1}"" /User:{2} & ", host, password, userid);
                }

                shutdownCommand.AppendFormat(@"shutdown /m \\{0} /t {1} ", host, dwDelay);


                switch (flags)
                {
                case var @case when @case == ShutdownFlags.LegacyShutdown:
                {
                    shutdownCommand.Append(" / s ");

                    break;
                }

                case var case1 when case1 == ShutdownFlags.LegacyForcedShutdown:
                {
                    shutdownCommand.Append(" /s /f ");

                    break;
                }

                case var case2 when case2 == ShutdownFlags.LegacyReboot:
                {
                    shutdownCommand.Append(" /r ");

                    break;
                }

                case var case3 when case3 == ShutdownFlags.LegacyForcedReboot:
                {
                    shutdownCommand.Append(" /r /f ");

                    break;
                }
                }

                //   if (!string.IsNullOrEmpty(message))
                //    shutdownCommand.AppendFormat(" /c \"{0}\"", message);

                ProcessStartInfo pi = new ProcessStartInfo()
                {
                    Arguments              = shutdownCommand.ToString(),
                    FileName               = "cmd.exe",
                    CreateNoWindow         = true,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    UseShellExecute        = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = false
                };
                p.StartInfo = pi;
                p.Start();

                DialogResult dialogResult = MessageBox.Show(" This Computer will shutdown in 20s , Do you want to Cancel The Shutdown ? ", "Shutdown", MessageBoxButtons.YesNo);

                if (dialogResult == DialogResult.Yes)
                {
                    shutdownCommand1.AppendFormat(@"net use \\{0}\IPC$ ""{1}"" /User:{2} & ", host, password, userid);
                    shutdownCommand1.AppendFormat(@"shutdown /m \\{0} /a", host);

                    ProcessStartInfo pi1 = new ProcessStartInfo()
                    {
                        Arguments              = shutdownCommand1.ToString(),
                        FileName               = "cmd.exe",
                        CreateNoWindow         = true,
                        WindowStyle            = ProcessWindowStyle.Hidden,
                        UseShellExecute        = false,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = false
                    };
                    p1.StartInfo = pi1;
                    p1.Start();
                    //   p1.StartInfo = pi1;
                    // p1.Start();
                }
                else
                {
                    // Display process statistics until
                    // the user closes the program.
                    do
                    {
                        if (!p.HasExited)
                        {
                            // Refresh the current process property values.
                            p.Refresh();
                            Debug.WriteLine("");

                            // Display current process statistics.

                            Debug.WriteLine("  Process: " + p.StartInfo.FileName);
                            Debug.WriteLine("Arguments: " + p.StartInfo.Arguments.ToString());
                            Debug.WriteLine("-------------------------------------");
                            if (p.Responding)
                            {
                                Debug.WriteLine("Status = Running");
                            }
                            else
                            {
                                Debug.WriteLine("Status = Not Responding");
                            }
                        }

                        error += p.StandardError.ReadToEnd();
                        Debug.WriteLine("error: " + error.ToString());
                    }while (!p.WaitForExit(1000));

                    Debug.WriteLine("");
                    Debug.WriteLine("Process exit code: {0}", p.ExitCode);

                    if ((p.ExitCode != 0))
                    {
                        throw new Exception(error);
                    }
                }
            }
            finally
            {
                if (!(p == null))
                {
                    p.Close();
                }
            }
        }
Esempio n. 11
0
        /// <summary>The call shutdown.</summary>
        /// <param name="shutdownFlag">The shutdown flag.</param>
        /// <param name="force">The force.</param>
        /// <exception cref="PlatformNotSupportedException">'GetCurrentProcess' method missing from 'kernel32'!</exception>
        private static void CallShutdown(ShutdownFlags shutdownFlag, bool force)
        {
            if (!CheckEntryPoint("kernel32.dll", "GetCurrentProcess"))
            {
                throw new PlatformNotSupportedException("'GetCurrentProcess' method missing from 'kernel32.dll'!");
            }

            // if force append to flag
            if (force)
            {
                shutdownFlag = shutdownFlag | ShutdownFlags.Force;
            }

            // open current process tokens
            var currentProcess = NativeMethods.GetCurrentProcess();
            var @null = IntPtr.Zero;

            // request privileges
            if (CheckEntryPoint("advapi32.dll", "OpenProcessToken"))
            {
                // open process token
                if (!NativeMethods.OpenProcessToken(currentProcess, TokenAdjustPrivileges | TokenQuery, ref @null))
                {
                    // failed...
                }

                // lookup privilege
                NativeMethods.LuidAtt luid;
                luid.Count = 1;
                luid.Luid = 0;
                luid.Attr = SePrivilegeEnabled;
                if (!NativeMethods.LookupPrivilegeValue(null, SeShutdownName, ref luid.Luid))
                {
                    // failed...
                }

                // adjust privileges and call shutdown
                if (NativeMethods.AdjustTokenPrivileges(@null, false, ref luid, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    // failed...
                }
            }

            // assume pre 2000, and call exit windows anyway
            // call exitWindows api
            if (NativeMethods.ExitWindowsEx((int)shutdownFlag, 0))
            {
                // failed...
            }
        }
Esempio n. 12
0
 public static extern bool ExitWindows(ShutdownFlags Flag, int Reason);
Esempio n. 13
0
 public static extern bool ExitWindowsEx(ShutdownFlags flags, ShutdownReason reason);