rshea0
rshea0

Reputation: 12259

Run code on WinForms app close and computer shutdown?

I want my C# WinForms app to run some code when either the app is closed, or the computer is shutdown (via the startmenu, I know it wont work if they pull the plug :P).

Basically I have some log files that I need the app to upload to an FTP server on shutdown.

How can I do this?

Upvotes: 1

Views: 3677

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48590

I think you should concentrate on doing your upload on shutting down of your app and not on shutting down of computer because when a computer is shutting down it will not have enough resources & time to do your work(upload and stuff). Use the Form_Closing event of your app to do your work when app's closing is called or you can use Form_Closed event to fire when your app is about to close.

Closing event Closed Event

Upvotes: 0

SharePoint Newbie
SharePoint Newbie

Reputation: 6082

You can detect your application shutting down by either intercepting the FormClosing event.

You can detect widows shutdown, logoff, suspend, etc using SystemEvents. I recommend not using the system events as you may not get enough time to perform an upload to a remote server (I think the default is 3 seconds).

Upvotes: 3

Joe White
Joe White

Reputation: 97838

Hook your form's FormClosing event. This will be fired any time the form closes, whether in response to the user closing it, the program calling Close, Windows shutting down, etc.

If you need to know which sort of exit you're dealing with, the FormClosingEventArgs has a CloseReason property (of type CloseReason) that will tell you why the window is being closed; it includes values like UserClosing and WindowsShutDown.

You may not be able to upload to an FTP server on Windows shutdown, though. In Windows Vista and 7, apps only get 2 seconds to shut down before Windows reserves the right to forcibly terminate them. You might be better off saving your log locally, and uploading it the next time your app starts.

Upvotes: 1

Related Questions