Determining app close by User or Windows
-
I have a C# Windows Form that contains the logic to display an icon in the systray. I have that form hidden (visible = false). When the user clicks the systray icon I unhide the form (visible = true) to allow the user to change some settings. When the user finishes changing the settings he can click the close button (the X in the top right corner). In the frm.closing event I have this: this.Visible = false; e.Cancel = true; That code will hide the form for later use and it keeps the application from exiting. Life is good UNTIL the user goes to shutdown the computer. During the shutdown process Windows goes to close my application; but my app sends Windows the Cancel signal and so Windows never shuts down. I’m about ready to hack something up with WndProc but I was hoping there might be some way to tell if whether my app is being closed by Windows or by a click of the close button (the X in the top right corner). Thanks.
-
I have a C# Windows Form that contains the logic to display an icon in the systray. I have that form hidden (visible = false). When the user clicks the systray icon I unhide the form (visible = true) to allow the user to change some settings. When the user finishes changing the settings he can click the close button (the X in the top right corner). In the frm.closing event I have this: this.Visible = false; e.Cancel = true; That code will hide the form for later use and it keeps the application from exiting. Life is good UNTIL the user goes to shutdown the computer. During the shutdown process Windows goes to close my application; but my app sends Windows the Cancel signal and so Windows never shuts down. I’m about ready to hack something up with WndProc but I was hoping there might be some way to tell if whether my app is being closed by Windows or by a click of the close button (the X in the top right corner). Thanks.
Implement the
IMessageFilter
interface and add an instance of your implementation usingApplication.AddMessageFilter
(this can degrade performance severely if not implemented correctly / efficiently). Watch for theWM_QUERYENDSESSION
(0x0011, cancelable) orWM_ENDSESSION
(0x0016). Alternatively, you can overrideWndProc
in your main application window (the form you pass toApplication.Run
, for example) and do the same thing. Windows sends this message when shutting down. You can returnfalse
to attempt to prevent Windows from shutting down (it most likely will), or just returntrue
and close your application or do whatever you need to.Microsoft MVP, Visual C# My Articles