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.
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.
If you add the System.Windows.Forms reference to your project, then you can find in this namespace the Application class that has static methods. One of them is what you want/need/seeking, and it is called "SetSuspendState". I used this function in the past, and with it I succeed to shut down my computer easily. There are options how you want to shut down your computer with this function. It takes 3 parameters. First the enum PowerState (Hibernate or Suspend), second the bool force, and third the bool disableWakeEvent. You can read about this function more extendly in the internet. The following execution line will shut down your computer as you expected (I hope so):
Works starting with windows XP, not available in win 2000 or lower:
This is the quickest way to do it:
Otherwise use P/Invoke or WMI like others have said.
Edit: how to avoid creating a window
This thread provides the code necessary: http://bytes.com/forum/thread251367.html
but here's the relevant code:
Usage:
or
If you want to shut down computer remotely then you can use
on any button click
**Elaborated Answer...