¿Cómo puedo crear una aplicación .NET Windows Forms que solo se ejecute en la bandeja del sistema?

Resuelto xyz asked hace 15 años • 13 respuestas

¿Qué debo hacer para que una aplicación de Windows Forms pueda ejecutarse en la bandeja del sistema?

No es una aplicación que pueda minimizarse en la bandeja, sino una aplicación que solo existirá en la bandeja, con nada más que

  • un icono
  • una información sobre herramientas, y
  • un menú de " clic derecho ".
xyz avatar Jun 15 '09 16:06 xyz
Aceptado

El artículo del proyecto de código Creación de una aplicación de bandeja de tareas ofrece una explicación muy simple y un ejemplo de cómo crear una aplicación que solo existe en la bandeja del sistema.

Básicamente, cambie la Application.Run(new Form1());línea Program.cspara iniciar una clase que herede de ApplicationContexty hacer que el constructor de esa clase inicialice unNotifyIcon

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new MyCustomApplicationContext());
    }
}


public class MyCustomApplicationContext : ApplicationContext
{
    private NotifyIcon trayIcon;

    public MyCustomApplicationContext ()
    {
        // Initialize Tray Icon
        trayIcon = new NotifyIcon()
        {
            Icon = Resources.AppIcon,
            ContextMenu = new ContextMenu(new MenuItem[] {
                new MenuItem("Exit", Exit)
            }),
            Visible = true
        };
    }

    void Exit(object sender, EventArgs e)
    {
        // Hide tray icon, otherwise it will remain shown until user mouses over it
        trayIcon.Visible = false;

        Application.Exit();
    }
}
Fawzan Izy avatar Apr 20 '2012 16:04 Fawzan Izy

Como dice mat1t, debe agregar un NotifyIcon a su aplicación y luego usar algo como el siguiente código para configurar la información sobre herramientas y el menú contextual:

this.notifyIcon.Text = "This is the tooltip";
this.notifyIcon.ContextMenu = new ContextMenu();
this.notifyIcon.ContextMenu.MenuItems.Add(new MenuItem("Option 1", new EventHandler(handler_method)));

Este código muestra el icono solo en la bandeja del sistema:

this.notifyIcon.Visible = true;  // Shows the notify icon in the system tray

Será necesario lo siguiente si tiene un formulario (por cualquier motivo):

this.ShowInTaskbar = false;  // Removes the application from the taskbar
Hide();

El clic derecho para obtener el menú contextual se maneja automáticamente, pero si desea realizar alguna acción con un clic izquierdo, deberá agregar un controlador de clic:

    private void notifyIcon_Click(object sender, EventArgs e)
    {
        var eventArgs = e as MouseEventArgs;
        switch (eventArgs.Button)
        {
            // Left click to reactivate
            case MouseButtons.Left:
                // Do your stuff
                break;
        }
    }
ChrisF avatar Jun 15 '2009 09:06 ChrisF

Núcleo .NET

Adapté la respuesta aceptada a .NET Core, utilizando los reemplazos recomendados para clases obsoletas:

  • Menú Contextual -> Menú ContextualStrip
  • Elemento de menú -> Elemento de menú ToolStrip

Programa.cs

namespace TrayOnlyWinFormsDemo
{
    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            ApplicationConfiguration.Initialize();
            Application.Run(new MyCustomApplicationContext());
        }
    }
}

MiContextoAplicaciónPersonalizada.cs

using TrayOnlyWinFormsDemo.Properties;  // Needed for Resources.AppIcon

namespace TrayOnlyWinFormsDemo
{
    public class MyCustomApplicationContext : ApplicationContext
    {
        private NotifyIcon trayIcon;

        public MyCustomApplicationContext()
        {
            trayIcon = new NotifyIcon()
            {
                Icon = Resources.AppIcon,
                ContextMenuStrip = new ContextMenuStrip()
                {
                    Items = { new ToolStripMenuItem("Exit", null, Exit) }
                },
                Visible = true
            };
        }

        void Exit(object? sender, EventArgs e)
        {
            trayIcon.Visible = false;
            Application.Exit();
        }
    }
}
MarredCheese avatar Apr 01 '2022 02:04 MarredCheese