We have an (C#/.NET) application running on a Windows embedded target that requires the machine to be shut down at the push of a button. Ideally I'd like the program to exit and perform its cleanup (including putting attached hardware into a safe state) before the shutdown takes place. But of course once the program has closed I can't execute the shutdown command! So can this be done?
Asked
Active
Viewed 872 times
1
-
Push of which button? On the machine itself or your program's? – AgentFire May 23 '14 at 08:49
-
We have an LCD screen with a 4-button keypad on it. There is a menu option for shutting down. – Julian Gold May 23 '14 at 09:00
-
Updated the answer again, then. – AgentFire May 23 '14 at 09:01
3 Answers
2
Sure it can be done, and it is very easy.
Start a process that issues "shutdown /s", THEn exit your program.

TomTom
- 61,059
- 10
- 88
- 148
1
Implement the Application.ApplicationExit
event (winforms) which will be called in any case your application is being closed.
For WPF:
https://stackoverflow.com/a/20347268/558018
From C#, the best way to shutdown is:
shutdown.exe /f /r /t 0
Execute the code through Process.Start(..)
and your computer will immediately begin its shutdown process.
Of course, before you execute this, you should do your "cleanup" procedures.
1
How to shut down the computer from C# took from here :
Works starting with windows XP, not available in win 2000 or lower:
This is the quickest way to do it:
Process.Start("shutdown","/s /t 0");
Otherwise use P/Invoke or WMI like others have said.

Community
- 1
- 1

Valentyn Vynogradskiy
- 633
- 1
- 6
- 22
-
This shuts the computer down but does not guarantee graceful exit. So I combine this with the Exit event from the WPF and I'm good, I guess? – Julian Gold May 23 '14 at 09:04