0
votes

I have this winform app that tracks battery life, if I close the app during an "alt+tab" (like in the pic below) it closes the app completely.

enter image description here

I want to program the close button (if this is possible) to minimize the app to the system tray instead of closing it completely.

I have not seen any similar solutions for this, all I see is disabling the alt+tab on a winforms app.

I want to do this because if I close the app the battery percentage wont be monitored anymore, I just want to know if this is possible though.

1
Use the FormClosing event as shown in the linked question and set e.Cancel to true after checking any validation logic you need. Make sure not to prevent closing if e.CloseReason == CloseReason.WindowsShutDown so that your program doesn't interrupt the shutdown process. - 41686d6564
@41686d6564 oh yeah, I did not think of the form closing event. Thank you for pointing that out! - JD Dalmao

1 Answers

0
votes

In order to minimize to system tray first add NotifyIcon on your form from Toolbox. And then add this code accordingly.

private System.Windows.Forms.ContextMenu notifyMenu;
private System.Windows.Forms.MenuItem notifyMenuItemClose;
public static bool close = false;

public ApplicationWindow()
{
    InitializeComponent();
}

private void ApplicationWindow_Load(object sender, EventArgs e)
{
    this.notifyMenu = new System.Windows.Forms.ContextMenu();
    this.notifyMenuItemClose = new System.Windows.Forms.MenuItem();
    this.notifyMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { this.notifyMenuItemClose });
    this.notifyMenuItemClose.Index = 0;
    this.notifyMenuItemClose.Text = "Exit";
    this.notifyMenuItemClose.Click += new System.EventHandler(this.notifyMenuItemClose_Click);
    this.notifyAppIcon.ContextMenu = this.notifyMenu;

}

private void notifyMenuItemClose_Click(object sender, EventArgs e)
{
    close = true;
    this.Close();
}

private void ApplicationWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    if (close)
    {
        e.Cancel = false;
    }
    else
    {
        WindowState = FormWindowState.Minimized;
        e.Cancel = true;
    }
}

private void notifyAppIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
    if (e.Button==MouseButtons.Left)
    {
        this.Show();
        WindowState = FormWindowState.Normal;
    }
}