Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Canceling closing of a form prevents it from closed on Windows shutdown

 Private Sub frmMain_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    e.Cancel = True
    Me.WindowState = FormWindowState.Minimized
End Sub

Hello!

I am using this simple code above. However if the application is open while I am shutting down the computer, Windows waits until it's closed or wants me to terminate it in order to continue. I couldn't find a way to know if the user is trying to close application or the Windows is. All I know is, in both situations Windows sends close message to the window and this doesn't really help me. I can think of some other ways yet there should be a "clear" way of knowing.

Thanks in advance :)

like image 289
gunakkoc Avatar asked Nov 28 '25 04:11

gunakkoc


2 Answers

There is also a close reason:

Protected Overrides Sub OnFormClosing(ByVal e As FormClosingEventArgs)
  If e.CloseReason <> CloseReason.WindowsShutDown Then
    e.Cancel = True
    Me.WindowState = FormWindowState.Minimized
  End If
End Sub
like image 59
LarsTech Avatar answered Nov 30 '25 19:11

LarsTech


You should be able to implement a close reason enumeration from this list. This will allow you to make it so that your computer will shutdown. You will have to implement the WindowsShutDown and/or TaskManagerClosing enumeration into your e.CloseReason.

like image 36
Bazinga Avatar answered Nov 30 '25 18:11

Bazinga