Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restarting Windows from within a .NET application

Tags:

c#

.net

winforms

How could I restart or shutdown Windows using the .NET framework?

like image 926
Terenced Avatar asked Jan 20 '09 18:01

Terenced


2 Answers

The following code will execute the shutdown command from the shell:

// using System.Diagnostics;  class Shutdown {     /// <summary>     /// Windows restart     /// </summary>     public static void Restart()     {         StartShutDown("-f -r -t 5");     }      /// <summary>     /// Log off.     /// </summary>     public static void LogOff()     {         StartShutDown("-l");     }      /// <summary>     ///  Shutting Down Windows      /// </summary>     public static void Shut()     {         StartShutDown("-f -s -t 5");     }      private static void StartShutDown(string param)     {         ProcessStartInfo proc = new ProcessStartInfo();         proc.FileName = "cmd";         proc.WindowStyle = ProcessWindowStyle.Hidden;         proc.Arguments = "/C shutdown " + param;         Process.Start(proc);     } } 

(Source: http://dotnet-snippets.de/dns/c-windows-herrunterfahren-ausloggen-neustarten-SID455.aspx

like image 190
Dirk Vollmar Avatar answered Sep 20 '22 02:09

Dirk Vollmar


I don't know a pure .NET way to do it. Your options include:

  • P/Invoke the ExitWindowsEx Win32 function
  • Use Process.Start to run shutdown.exe as already suggested.
like image 21
driis Avatar answered Sep 21 '22 02:09

driis