GurdeepS
GurdeepS

Reputation: 67213

Making a winforms app power-aware

How can I make my apps resilient to power cuts? For example, how can I make an app detect when the power button on the machine is held?

Also, if this happens, what would you want an application to do? Save any unsaved work (but this would be in another file and not overwriting the existing file as the user may not want to overwrite his/her work which has changed but not been saved).

What would you do in this event and how?

Thanks

Upvotes: 1

Views: 213

Answers (4)

CodesInChaos
CodesInChaos

Reputation: 108790

There are so many ways your process can suddenly die. From power outage, the reset button, to the taskmanager or system crashes. You can't predict it.

Regularly save to a temp-file (preferably in an atomic/transactional way) like Word does, so that at whichever time the program terminates you can restore to a valid state. The atomicity is important if your program dies while saving so you don't end up with a corrupted file.

Upvotes: 0

Neowizard
Neowizard

Reputation: 3017

You can't really tell when is the power going to die (what if the user unplugged the machine, nothing to do there). What you can do is be prepared for power out at every step. For instance, you can write the current state and data of the application to a file dedicated for this purpose. Another option is to provide checkpoints in the execution path where the partial result will be saved.

For every solution, remember also to write in your persistent data storage if the application terminated normally or not

It all depends on the type of data in application states you use. The good news is, it's always possible if it's important enough

Upvotes: 2

Shoban
Shoban

Reputation: 23016

I don't think you will be able to detect unusual shut down/powercut. One idea is to save data to the temp file periodically and update the original file only when the user saves the settings. When this is done clear the temp file.

During start up check if the temp file has any data. If yes then there was an unusual shutdown and give an option for the user to "restore" from the temp file.

Upvotes: 0

Aamir
Aamir

Reputation: 15546

I am afraid you can't do anything with this. There is no special event fired in such a case.

Upvotes: 0

Related Questions