Search code examples
vb.netnotifyicon

vb.net how do I make an application that only has a notifyicon and no windows form?


I want to make an application that only has a notifyicon and doesn't have any visible window form when it starts up. I see some example sort of like what I want to do for c#, but I don't see how to do this in vb.net project.


Solution

  • A form is not strictly necessary. You can instantiate a NotifyIcon and use that without creating a form:

    Public Class AppContext
        Inherits ApplicationContext
    
        Private notifyIcon As NotifyIcon
        Private appActive As Boolean
    
        Public Sub New()
            AddHandler Application.ApplicationExit, AddressOf OnApplicationExit
    
            notifyIcon = New NotifyIcon()
            notifyIcon.Icon = My.Resources.ActiveIcon
            notifyIcon.Text = "The app is active."
    
            AddHandler notifyIcon.MouseClick, AddressOf OnIconMouseClick
    
            appActive = True
            notifyIcon.Visible = True
    
        End Sub
    
        Private Sub OnApplicationExit(ByVal sender As Object, ByVal e As EventArgs)
            If notifyIcon IsNot Nothing Then
                notifyIcon.Dispose()
            End If
        End Sub
    
        Private Sub OnIconMouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
    
            If e.Button = MouseButtons.Left Then
                appActive = Not appActive
                notifyIcon.Icon = If(appActive, My.Resources.ActiveIcon, My.Resources.InactiveIcon)
                notifyIcon.Text = If(appActive, "The app is active.", "The app is not active.")
            Else
                If MsgBox("Do you want to Exit?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    notifyIcon.Visible = False
                    ExitThread()
                End If
            End If
        End Sub
    
    End Class
    

    And then start your app from a Sub Main:

    Public Module EntryPoint
        Public Sub Main()
            Dim ctx As New AppContext()
            Application.Run(ctx)
        End Sub
    End Module