How to shut down the computer from C#

2019-01-01 03:04发布

What's the best way to shut down the computer from a C# program?

I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.

18条回答
何处买醉
2楼-- · 2019-01-01 03:54

You can launch the shutdown process:

  • shutdown -s -t 0 - Shutdown
  • shutdown -r -t 0 - Restart
查看更多
看风景的人
3楼-- · 2019-01-01 03:55

Just to add to Pop Catalin's answer, here's a one liner which shuts down the computer without displaying any windows:

Process.Start(new ProcessStartInfo("shutdown", "/s /t 0") {
  CreateNoWindow = true, UseShellExecute = false
});
查看更多
梦该遗忘
4楼-- · 2019-01-01 03:58

I tried roomaroo's WMI method to shutdown Windows 2003 Server, but it would not work until I added `[STAThread]' (i.e. "Single Threaded Apartment" threading model) to the Main() declaration:

[STAThread]
public static void Main(string[] args) {
    Shutdown();
}

I then tried to shutdown from a thread, and to get that to work I had to set the "Apartment State" of the thread to STA as well:

using System.Management;
using System.Threading;

public static class Program {

    [STAThread]
    public static void Main(string[] args) {
        Thread t = new Thread(new ThreadStart(Program.Shutdown));
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        ...
    }

    public static void Shutdown() {
        // roomaroo's code
    }
}

I'm a C# noob, so I'm not entirely sure of the significance of STA threads in terms of shutting down the system (even after reading the link I posted above). Perhaps someone else can elaborate...?

查看更多
墨雨无痕
5楼-- · 2019-01-01 03:59

Different methods:

A. System.Diagnostics.Process.Start("Shutdown", "-s -t 10");

B. Windows Management Instrumentation (WMI)

C. System.Runtime.InteropServices Pinvoke

D. System Management

After I submit, I have seen so many others also have posted...

查看更多
只靠听说
6楼-- · 2019-01-01 04:02

Note that shutdown.exe is just a wrapper around InitiateSystemShutdownEx, which provides some niceties missing in ExitWindowsEx

查看更多
余生请多指教
7楼-- · 2019-01-01 04:06

Use shutdown.exe. To avoid problem with passing args, complex execution, execution from WindowForms use PowerShell execute script:

using System.Management.Automation;
...
using (PowerShell PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript("shutdown -a; shutdown -r -t 100;");
    // invoke execution on the pipeline (collecting output)
    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
} 

System.Management.Automation.dll should be installed on OS and available in GAC.

Sorry for My english.

查看更多
登录 后发表回答