kampi
kampi

Reputation: 2484

How to Programmatically Determine if Windows is Shutting Down?

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!

Upvotes: 5

Views: 3250

Answers (3)

Andrew Lambert
Andrew Lambert

Reputation: 1909

Call GetSystemMetrics with index SM_SHUTTINGDOWN (0x2000).

Upvotes: 8

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215617

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.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 613572

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.

Upvotes: 3

Related Questions