Getting a formless C# program to close itself during shutdown/restart? - c#

I'm writing a program which creates no forms at all until one is required. The problem is, it's preventing shutdown from continuing automatically. I've seen discussions about adding an if to form closing events to check if it's due to shutdown, but as I've said, my program is meant to have no forms at all until required.
Is there any event or some other method that will allow me to know when my program should be closing itself to allow for Windows to shut itself down automatically? And it's not multithreaded.

You can use the SystemEvents class, to "listen to" users logging out, or shutting down.
If I understand the documentation correctly (and a deep study with Reflector confirms this):
The systemevents will spawn a new thread that receives the messages from windows (it has its own messagepump).
When an event is received, your code will be called, from the new thread. You should be aware of this.

You could always add a dummy form which you open minimized, with no icon on the taskbar - it won't have any visual impact, but will be sent the form closing event - where you could note the shutdown event, and presumably shut down/stop whatever else there is that your application is doing.

Handling the Microsoft.Win32.SystemEvents.SessionEnding event, and checking if it's an actual shutdown with System.Environment.HasShutdownStarted

Related

Environment.Exit(0) or Application.Exit() after all, which to use? [duplicate]

Following are the ways by which we can exit an application:
Environment.Exit(0)
Application.Exit()
Form.Close()
What is the difference between these three methods and when to use each one?
The proper method would be Application.Exit(). According to the Documentation, it terminates all message loops and closes all windows thus giving your forms the possibility to execute their cleanup code (in Form.OnClose etc).
Environment.Exit would just kill the process. If some form has e.g. unsaved changes it would not have any chances to ask the user if he wants to save them. Also resources (database connections etc.) could not be released properly, files might not be flushed etc.
Form.Close just does what it says: it closes a form. If you have other forms opened (perhaps not now but in some future version of your application), the application will not terminate.
Keep in mind that if you use multithreading, Application.Exit() will not terminate your threads (and thus the application will keep working in the background, even if the GUI is terminated). Therefore you must take measures to kill your threads, either in the main function (i.e. Program.Main()) or when in the OnClose event of your main form.
they are all fine.
but form.Close() won't close your application
it closes the form and after that
the main-method returns an int (exitcode).
if you want that your application exits with exitcodes use
Environmet.Exit(exitcode) or return the exitcode in the main-method

C# WinForms Tray application - not catching windows shutdown events

I'm writing a program that monitors state. It launches main window (LoginForm) to ask for user credentials, then hides the form. After that LoginForm inits NotifyIcon and all the remaining work is being done with LoginForm hidden. I've implemented all the clean-up work in FormClosing event of LoginForm. During normal exit process everything works perfectly.
The problem is that the program sits in tray all the time and I tend to forget to exit it before shutting down windows - program doesn't save the state on shutdown event.
I've read through many forums and docs, and from what I've read events FormClosing/FormClosed + SessionEnding/SessionEnded must fire anyway. But it looks like they just don't fire. Can't even cancel shutdown in SessionEnding (with stupid e.Cancel=true) - program disappears without reaching the place.
I've made myself a small debugging library to write out debug information into a file with instant flashing of cache. I've added debug messages to all the events. When I try to log off user in Windows (same as shutting down) for a test - I see no events being triggered usually, just the program vanishes. No exceptions I could catch, no events, etc. When exitting program manually or through "taskkill /IM " - I see all the expected debug printout. What's even more interesting - sometimes the program does reach closing events and does proper clean-up job during Windows shutdown.
Wasted a few days on this already. Overriden WndProc as suggested in MS article - program doesn't reach WndProc as well (to ensure it comes first before closing the form). Tried instead of FormClosing event to override OnClosing of LoginForm - no luck. Added UnhandledException handler, Microsoft.Win32.SessionEnding, Microsoft.Win32.SessionEnded, Form.FormClosing, Form.FormClosed event handlers - no luck.
I suspect this is either a problem of hidden forms or that some kind of exception is happening during shutdown only (resources disposed?). How can I find why that's happening? Is there some simple way to simulate Windows shutdown for single application to make debugging in VS possible? I've tried RMTool - for some reason it fails to simulate shutdown and program just ignores it.
Update: Program uses System.Timers.Timer to regularly poll server for any changes.
I've done some research into this, basically, after Windows XP they altered the way that shutdowns were handled.
You cannot block or capture the shutdown event reliably using the form_closing events etc.
You must use a new API to do so. There is a complete example here: http://bartdesmet.net/blogs/bart/archive/2006/10/25/Windows-Vista-2D00-ShutdownBlockReasonCreate-in-C_2300_.aspx
You should be able to call the function to block shutting down (display a message such as 'saving changes...') and then save and exit your application in the background. Once your program quits, it should allow windows to continue shutting down.
I think windows is simply configured to automatically shutdown all applications regardless and hence the application has no chance to catch SessionEnding events and so on : have a look at http://www.addictivetips.com/windows-tips/disable-automatic-termination-of-applications-during-shutdown-in-windows-7/ or check your configuration at Computer Configurations > Administrative Templates > System > Shutdown Options.

Password Protect Winforms Application

I have a simple WinForms application that runs in the system tray. Is it possible to password protect the program from closing if a user tries to close it from task manager?
Ideally I want to keep a user from closing the process but if windows is restarted, I want it to close without being prompted. Much like antivirus programs.
If a user has the correct permissions they will be able to kill your process from the Task Manager.
That said as #fujiFX mentions in his comment the FormClosing event is a good start and better than nothing.
The FormClosing event occurs as the form is being closed. When a form is closed, it is disposed, releasing all resources associated with the form. If you cancel this event, the form remains opened. To cancel the closure of a form, set the Cancel property of the FormClosingEventArgs passed to your event handler to true.
It's hard to do, but you can create two applications, one is main program and two is helper. If helper is killed, then main app restarts it. If main app is killed, then helper restarts main app.
You can make this verification on YourService.Stop method (assuming you're using a Windows Service thus inheriting from ServiceBase), but as far as I know you cannot prevent the user from killing the proccess, just to close the app (two different things in Windows).

How to tell whether closing via close button or via Application.Shutdown in WPF?

I added a code for standard "Are you sure you want to exit?" message inside the this.Closing
event of my main window.
It works as expected for closing from the gui, however I would like to disable this check when the application is closed via Application.Shutdown().
There is no event in the Application fired before the window gets closed and the Shutdown method cannot be overriden.
How can I detect what invoked the closing of the window?
Disclaimer: I'd make this a comment rather than an answer if I could as it is a dirty hack (not a clean one). But if you really need something and no better solutions present itself I'll post it anyway to hopefully help...
If you're definitely not in a position to control / hook the parts of the code base that are calling application shutdown, then the possibility is to find something else that responds to the shutdown that you can trip before your window closes.
My (not so ideal) thought on that is to set up another hidden window (SO: Loading a WPF Window without showing it) that the user wont interact with but the application will close on shutdown.
In the closing event of that window you can set a flag to indicate the application is shutting down. Then in your main window's closing event you can react to that flag.
The big issue to tackle is configuring things so that the hidden window will always close before the Main Window(s) safely.
I did some limited tests with MainWindow.Xaml as the application Startupuri, and creating the hidden window from the application.onstartup event and found the hidden window would close first - but I wouldn't want to gaurantee that in all scenerios! Actually getting this working and tested adequately could be a lot of work - as I said it's a last restort dirty hack.
Who calls Application.Shutdown()? If you are in Charge of that just set a flag indicating that you did it and check for that flag in the Closing event handler.

Which event fires when we cancel some App by Windows Task Manager?

I need to know which event fires within an WPF application if I cancel it by Windows Task Manager?
The idea is to terminate internal App. job accurately.
Thank you!
When you use the "Processes" tab there is no event, because your process is simply killed.
When you use the "Applications" tab, a normal WM_CLOSE message is sent to the top level of your application. See the last answer here on how to detect this in a WPF application.
The idea is to terminate internal App. job accurately.
You can't do this reliably. If the user is ending the application that way, something has either gone badly wrong or they simply don't care. There's nothing you can do, you're toast. Don't worry about cleaning up after yourself: the operating system will do that for you, no thank you required.
The best thing that you can do is handle the standard close events. Those will get triggered if the user requests to end your app in a polite way, either via the normal means or through Task Manager (Task Manager will try to ask nicely first if the user clicks "End Task" from the "Applications" tab). But since I assume you're already doing that, you've done all that you can.
Handling the event from Task Manager is not possible as the way it works for ungracefull shut downs of applications.
However, you can try to handle the Application class' SessionEnding event which is described in MSDN at below link:
http://msdn.microsoft.com/en-us/library/system.windows.application.sessionending.aspx

Categories

Resources