1

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?

Julian Gold
  • 1,246
  • 2
  • 19
  • 40

3 Answers3

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.

MSDN Example.

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.

Community
  • 1
  • 1
AgentFire
  • 8,944
  • 8
  • 43
  • 90
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
  • 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