TKK_E32230371/UPSNet/WindowsShutdown.cs

140 lines
4.2 KiB
C#

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace UPSNet
{
public static class WindowsShutdown
{
// Import Windows API functions
[DllImport("user32.dll", SetLastError = true)]
private static extern bool ExitWindowsEx(uint uFlags, uint dwReason);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool AbortSystemShutdown(string lpMachineName);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool InitiateSystemShutdown(
string lpMachineName,
string lpMessage,
uint dwTimeout,
bool bForceAppsClosed,
bool bRebootAfterShutdown);
// Shutdown flags
private const uint EWX_LOGOFF = 0x00;
private const uint EWX_SHUTDOWN = 0x01;
private const uint EWX_REBOOT = 0x02;
private const uint EWX_FORCE = 0x04;
private const uint EWX_POWEROFF = 0x08;
/// <summary>
/// Shutdown modes
/// </summary>
public enum ShutdownMode
{
Shutdown,
Restart,
LogOff,
ForceShutdown,
ForceRestart,
PowerOff
}
/// <summary>
/// Shuts down Windows with specified mode
/// </summary>
public static bool Shutdown(ShutdownMode mode)
{
uint flags = 0;
switch (mode)
{
case ShutdownMode.Shutdown:
flags = EWX_SHUTDOWN;
break;
case ShutdownMode.Restart:
flags = EWX_REBOOT;
break;
case ShutdownMode.LogOff:
flags = EWX_LOGOFF;
break;
case ShutdownMode.ForceShutdown:
flags = EWX_SHUTDOWN | EWX_FORCE;
break;
case ShutdownMode.ForceRestart:
flags = EWX_REBOOT | EWX_FORCE;
break;
case ShutdownMode.PowerOff:
flags = EWX_POWEROFF;
break;
}
return ExitWindowsEx(flags, 0);
}
/// <summary>
/// Shuts down or restarts with a timeout and message
/// </summary>
public static bool TimedShutdown(bool restart, int timeoutSeconds = 30, string message = "") {
return InitiateSystemShutdown(
null, // Local computer
message, // Display message
(uint)timeoutSeconds, // Timeout period
true, // Force apps closed
restart); // Restart after shutdown
}
/// <summary>
/// Cancel pending shutdown
/// </summary>
public static bool CancelShutdown(){
return AbortSystemShutdown(null); // Null for local computer
}
/// <summary>
/// Aborts a pending shutdown
/// </summary>
public static void AbortShutdown(){
Process.Start("shutdown", "/a");
}
/// <summary>
/// Executes shutdown via command line (alternative method)
/// </summary>
public static bool CmdShutdown(ShutdownMode mode, int timeoutSeconds = 0)
{
string args = "";
switch (mode)
{
case ShutdownMode.Shutdown:
case ShutdownMode.ForceShutdown:
case ShutdownMode.PowerOff:
args = "/s";
break;
case ShutdownMode.Restart:
case ShutdownMode.ForceRestart:
args = "/r";
break;
case ShutdownMode.LogOff:
args = "/l";
break;
}
if (timeoutSeconds > 0)
{
args += " /t " + timeoutSeconds;
}
if (mode == ShutdownMode.ForceShutdown || mode == ShutdownMode.ForceRestart)
{
args += " /f";
}
Process p = Process.Start("shutdown", args);
if (p==null) return false;
return true;
}
}
}