Home All Groups Group Topic Archive Search About

How to close an application??

Author
20 Jan 2006 1:45 PM
pamelafluente
Hi Guys,

I have a small application which uses a NotifyIcon. The user can set
the program so that when he clicks on the form-cancel button "X", the
program will instead be minimized in the icon try. See code below.

My problem is that my code is problably too naive. In fact there is a
problem when one tries to shut dow or restart Windows. Windows does not
want to shut down!

Could anybody by so kind as to suggest me the correct approach to do
this. Is there a way to detect the the closing is due to system restart
or shutdown?

Thank you very much in advance,

-Pam

-----------------------------------------------------------------------------

    Private PreventClosing As Boolean
'if this is set TRUE by the user, the program minimizes (instead of
closing) when "X" is pressed

    Private ShowInTaskbarSaved As Boolean
    Private WindowStateSaved As FormWindowState

'...

    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing

        If Me.PreventClosing Then
            Me.HideInTrayIcon()
            e.Cancel = True
        End If

    End Sub

    Private Sub HideInTrayIcon()

        Me.WindowStateSaved = Me.WindowState
        Me.WindowState = FormWindowState.Minimized
        Me.ShowInTaskbar = False
        Me.NotifyIcon1.Visible = True

    End Sub


'...
    Private Sub RestoreWindow()
        Me.NotifyIcon1.Visible = False
        Me.ShowInTaskbar = Me.ShowInTaskbarSaved
        Me.WindowState = Me.WindowStateSaved
        Me.Show()
        Me.Focus()
    End Sub

Author
20 Jan 2006 2:39 PM
AMercer
Try handling a SystemEvents.SessionEnded event.
Author
22 Jan 2005 8:04 PM
Crouchie
Use WndProc to QUERYENDSESSION

Private Shared WM_QUERYENDSESSION As Integer = &H11
Private Shared systemShutdown As Boolean = False
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_QUERYENDSESSION Then
        MessageBox.Show("queryendsession: this is a logoff, shutdown, or
reboot")
        systemShutdown = True
    End If
    ' If this is WM_QUERYENDSESSION, the closing event should be fired in
the base WndProc
    MyBase.WndProc(m)
End Sub 'WndProc
Private Sub Form1_Closing(ByVal sender As System.Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
    If (systemShutdown) Then
    ' reset the variable since they may cancel the shutdown
        systemShutdown = False
        If (DialogResult.Yes = _
                MessageBox.Show("My application", "Would you care to save
your work before logging off?", MessageBoxButtons.YesNo)) Then
                e.Cancel = True
        Else
                e.Cancel = False
        End If
    End If
End Sub

I hope that helps

Crouchie1998
BA (HONS) MCP MCSE