Start Windows Forms program in the background

Asked

Viewed 3,157 times

2

I developed a monitoring application using Windows Forms, but it has no need to have anything visual at the moment, so I would like when running it, it to be executed in the background (I would like the icon to stay where the anti-virus icons are,etc.).

I don’t have much experience with desktop applications and I’m not able to find a way to do it, someone could help?

  • 2

    I have a personal project at Github, a mini web server made in C#, that does just that. It starts only with an icon in the Windows notification bar, and when you right click on it a menu with the program options appears, when you left click a terminal screen appears, showing the log events.

2 answers

6


Minimize the application to the Tray system is done with the control NotifyIcon of Visual Studio.

NotifyIcon is in namespace System.Windows.Forms.

1. Notifyicon control

Drag and drop control NotifyIcon for your form and put your name on the same notifyIcon1.

2. Changing the Notifyicon icon

We need to change the icon of NotifyIcon for it to appear on system Tray, otherwise nothing will show. For this, put the following line of code in your form’s constructor:

public Form1()
{
    InitializeComponent();
    notifyIcon1.Icon = new Icon(GetType(), "placeholder.ico");
}

The icon must be a . ico and must be set to Embeddedresource in the icon properties after adding it to the project.

inserir a descrição da imagem aqui

3. Configuring the form

No . Cs of your Form, put the following:

private bool allowVisible;

protected override void SetVisibleCore(bool value) {
    if (!allowVisible) {
        value = false;
        if (!this.IsHandleCreated) CreateHandle();
    }
    base.SetVisibleCore(value);
}

protected override void OnFormClosing(FormClosingEventArgs e) {
    if (!allowClose) {
        this.Hide();
         e.Cancel = true;
    }
    base.OnFormClosing(e);
}

3. Showing the application

Enter the code below in the event DoubleClick of control NotifyIcon to display your application by double-clicking the icon on Tray system:

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
     allowVisible = true;
     Show();
}

Once you start your application, it will go straight to the Tray system with the icon you set earlier. To open the application, simply double-click on the icon on Tray system.

  • This code requires a form to be rendered to show the notification icon, and closes the application when the form is closed. This is a foreground execution and I don’t think it’s what the AP asked for.

  • @Renan No even. I just changed the logic of showing and hiding the form and it worked perfectly. I hope you didn’t downvote just because you thought it wouldn’t work.

  • Fair. I changed my vote to positive.

  • @Renan Justo. Thank you.

  • What surprised me is that calling the method hide remove it from the taskbar. I didn’t know this was possible.

4

If you take a quick look at the file Program.Cs of your project, you will probably see something like:

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

Emphasis on:

Application.Run(new Form1());

The method Run has more than one overload, and the default is not to receive any parameter. Remove your form, i.e.: change the code to:

Application.Run();

And see how your application starts without an open window.

You also won’t have anything in the taskbar, so just with that it gets complicated even close the program. You will only be able to close it with the task monitor (CTRLALTDEL).

Ok, let’s make some more changes. Add the following namespaces:

using System.Drawing; // esse é só pra encurtar o uso de uma classe de ícone
using System.reflection; // esse a gente usa pra pegar o ícone da aplicação

Now add a notification icon. It is a class object System.Windows.Forms.NotifyIcon and does not need to be attached to any form :)

NotifyIcon ni = new NotifyIcon()
{
    Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location), // pega o ícone da aplicação
    Text = "hello",
    Visible = true // porque o padrão para "Visible" é falso
};

The complete code looks like this:

using System;
using System.Drawing;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

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

            NotifyIcon ni = new NotifyIcon()
            {
                Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location),
                Text = "hello"
            };
            Application.Run();
        }
    }
}

I leave it to you now:

  • Run any logic from the other classes you have implemented;
  • Add events to the notification icon to open and close your forms;
  • Treat the closure of the application to remove it from the system tray.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.