2

I want to run an executable that saves an XML file on a local drive before the computer (running on Windows 7) gets shut down.

I know it is possible to run scripts before shutdown. This can be configured in Local Group Policy Editor under Computer Configuration --> Windows Settings --> Scripts(Startup/Shutdown).

I have tried to put my executable in the shutdown property, but it does not work. How can I run an executable before the computer gets shut down? How can I hook up the shutdown event?

migrated from stackoverflow.com Jan 21 '14 at 21:32

This question came from our site for professional and enthusiast programmers.

  • Have you tried to see why it didn't work at the system log? – Vinícius Gobbo A. de Oliveira Jan 21 '14 at 15:08
  • Also have you tried it using the task scheduler too? – RononDex Jan 21 '14 at 15:15
  • I found solution for similar question – Utamaru Jan 21 '14 at 15:17
7

Launching a process when the shutdown was initiated is a bad idea. At this stage the most likely outcome is to get back the error 1115 ERROR_SHUTDOWN_IN_PROGRESS.

A much better way is to install a service and register the service to receive shutdown notifications via RegisterServiceCtrlHandlerEx, see shutting down:

Service applications receive shutdown notifications in their handler routines. To register a service control handler, use the RegisterServiceCtrlHandlerEx function.

A C# service would do this by setting CanShutdown to true and then handling the OnShutdown event. It is important to be service, not an application, as shutdown can occur when no session is logged on and/or multiple sessions could be running when the shutdown occurs.

  • This does not always work. I've set CanShutdown to true, implemented OnShutdown which writes to a simple file. The file is never written to. Service runs as local system so I know it has permissions. – jjxtra Feb 18 '18 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.