5

I am making an application which runs on our every PC in random times. It works fine, however if the PC is currently shutting down, then I can't read the WMI and i get some errors. So I need to determinate if a PC is shutting down currently, and so i could avoid these errors. Does anyone has an idee?

Thanks!

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
kampi
  • 2,362
  • 12
  • 52
  • 91
  • possible duplicate of [How to detect Windows shutdown or logoff](http://stackoverflow.com/questions/6799955/how-to-detect-windows-shutdown-or-logoff) – Bob Kaufman Jan 28 '12 at 22:47
  • @BobKaufman Not a duplicate if actually about c, not c#. – GSerg Jan 28 '12 at 22:50

3 Answers3

7

Call GetSystemMetrics with index SM_SHUTTINGDOWN (0x2000).

Liam
  • 27,717
  • 28
  • 128
  • 190
Andrew Lambert
  • 1,869
  • 1
  • 17
  • 31
3

Create a hidden top-level window and listen for WM_ENDSESSION messages. The value of wParam will tell you whether the entire system is going down, or whether the user is logging off.

If your app is a console app then use SetConsoleCtrlHandler to register to receive shutdown notifications.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • And if your app is a service then use [RegisterServiceCtrlHandlerEx](http://msdn.microsoft.com/en-us/library/windows/desktop/ms685058.aspx). – Neil Jan 28 '12 at 23:36
  • 2
    FYI: While this suggestion will generally work - it will also fail in certain conditions. There is no way to guarantee which window will receive the message (in a multi-window application), as Windows does not broadcast the WM_ENDSESSION to all windows of an application. – SilverKnight Jan 04 '13 at 17:47
1

Any attempt to detect this situation will have a race condition: the system shutdown might start immediately after you detect that it's not shutting down, but before you try to perform the operations that won't work during shutdown. Thus your approach to fixing the problem is wrong. Instead you just need to handle the WMI read failures and determine if they're cause by system shutdown, and in this case abort the operation or proceed in whatever alternate way makes sense.

It might be possible to use a sort of synchronous shutdown detection mechanism where you can actually lock/delay the shutdown for a brief interval before it proceeds, and do your processing in that interval. If so, that would also be a safe approach without race conditions.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • 2
    You just need to quit the app when you get notified of shutdown. I don't see why there is a race. You can indeed block shutdown by handling the notification messages. – David Heffernan Jan 28 '12 at 23:41