Pregunta

¿Qué se debe hacer para que su aplicación .NET aparezca en la bandeja del sistema de Windows como icono?

¿Y cómo maneja los clics del mouse sobre dicho ícono?

¿Fue útil?

Solución

Primero, agregue un NotifyIcon Control a la forma. Luego, conecta el ícono Notificar para hacer lo que quieras.

Si desea que se oculte en la bandeja al minimizar, intente esto.

Private Sub frmMain_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize
    If Me.WindowState = FormWindowState.Minimized Then
        Me.ShowInTaskbar = False
    Else
        Me.ShowInTaskbar = True
    End If
End Sub

Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
    Me.WindowState = FormWindowState.Normal
End Sub

Ocasionalmente usaré el texto de globo para notificar a un usuario, eso se hace así:

 Me.NotifyIcon1.ShowBalloonTip(3000, "This is a notification title!!", "This is notification text.", ToolTipIcon.Info)

Otros consejos

Puede agregar el componente NotifyIcon de la caja de herramientas a su formulario principal.

Esto tiene eventos como MouseDoubleClick que puedes usar para manejar varios eventos.

Editar: debes asegurarte de establecer la propiedad Icon en un archivo .ico válido si quieres que se muestre correctamente en la bandeja del sistema.

Un pequeño y agradable tutorial sobre el uso de la clase NotifyIcon aquí: http: // www .developer.com / net / csharp / article.php / 3336751

Agregue el componente NotifyIcon a su formar. Y usa sus eventos para manejar los clics del mouse.

Esto muestra y maneja todas las combinaciones de clic del mouse para NotifyIcon

Más aquí: https://archive.codeplex.com/?p=notifyicon

Para ampliar la respuesta de Tom , me gustaría que el icono solo esté visible si la aplicación está minimizada.
Para hacer esto, configure Visible = False para NotifyIcon y use el siguiente código.

También tengo el siguiente código para ocultar el ícono durante el cierre para evitar que los íconos de la bandeja fantasma molestos que persisten después del cierre de la aplicación.

Private Sub Form_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize
    If Me.WindowState = FormWindowState.Minimized Then
        Hide()
        NotifyIcon1.Visible = True
        NotifyIcon1.ShowBalloonTip(3000, NotifyIcon1.Text, "Minimized to tray", ToolTipIcon.Info)
    End If
End Sub

Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
    Show()
    Me.WindowState = FormWindowState.Normal
    Me.Activate()
    NotifyIcon1.Visible = False
End Sub

Private Sub Form_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    NotifyIcon1.Visible = False
    Dim index As Integer
    While index < My.Application.OpenForms.Count
        If My.Application.OpenForms(index) IsNot Me Then
            My.Application.OpenForms(index).Close()
        End If
        index += 1
    End While
End Sub

Si desea agregar un menú del botón derecho:

VB.NET: Cómo hacer un menú de clic derecho para un icono de bandeja

Según el artículo (con modificaciones para el contexto):

Configuración del formulario para alojar el menú contextual del icono de la bandeja

  • En las propiedades, establezca FormBorderStyle en Ninguno.
  • Establezca ShowInTaskbar como False (porque no queremos que aparezca un icono en la barra de tareas cuando hacemos clic derecho en el icono de la bandeja).
  • Establezca StartPosition en Manual.
  • Establezca TopMost en True.
  • Agregue un ContextMenuStrip a su nuevo formulario y asígnele el nombre que desee.
  • Agregue elementos a ContextMenuStrip (para este ejemplo, simplemente agregue un elemento llamado " Salir ").

El código del formulario detrás se verá así:

Private Sub Form_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate
    Me.Close()
End Sub

Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ContextMenuStrip1.Show(Cursor.Position)
    Me.Left = ContextMenuStrip1.Left + 1
    Me.Top = ContextMenuStrip1.Top + 1
End Sub

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
    MainForm.NotifyIcon1.Visible = False
    End
End Sub

Luego, cambio el evento de mouse de notificación a este ( TrayIconMenuForm es el nombre de mi formulario para proporcionar el menú contextual):

Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
    Select Case e.Button
        Case Windows.Forms.MouseButtons.Left
            Show()
            Me.WindowState = FormWindowState.Normal
            Me.Activate()
            NotifyIcon1.Visible = False
        Case Windows.Forms.MouseButtons.Right
            TrayIconMenuForm.Show() 'Shows the Form that is the parent of "traymenu"
            TrayIconMenuForm.Activate() 'Set the Form to "Active", that means that that will be the "selected" window
            TrayIconMenuForm.Width = 1 'Set the Form width to 1 pixel, that is needed because later we will set it behind the "traymenu"
            TrayIconMenuForm.Height = 1 'Set the Form Height to 1 pixel, for the same reason as above
        Case Else
            'Do nothing
    End Select
End Sub
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top