Search code examples
vb.netsystem-tray

VB.Net program minimized not working


I have a code like below

 Private Sub InterfaceProg_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
    'program minimized
    Try
        If Me.WindowState = FormWindowState.Minimized Then
            Me.Visible = True
            NotifyIcon1.Visible = True
            NotifyIcon1.ShowBalloonTip(1, "Browser Bandwidth Optimizer", "Program Minimized", ToolTipIcon.Info)
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

The code is working fine but there is one problem. When i press the minimize button on top right, the program go to system tray When i press close button, the program also go to system also go to system tray.

i want to make the program go to system tray if user press close button only and minimized the program to taskbar if user press minimized. how to do it?


Solution

  • Use the FormClosing event instead of the Resize event:

    Private CloseAllowed As Boolean
    
    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If Not CloseAllowed And e.CloseReason <> CloseReason.WindowsShutDown Then
            Me.Hide()
            e.Cancel = True
            NotifyIcon1.Visible = True
            '' etc..
        End If
    End Sub
    

    You still need to give the user a way to exit the program. The context menu for the NotifyIcon is the usual approach. Add an Exit item:

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        CloseAllowed = True
        Me.Close()
    End Sub