简体   繁体   中英

How do I hide a window form when x is clicked and CLose through system tray ToolStripMenuItem

I am new to C# .Net, I was looking for a way to hide my form window when 'X' on the window (Close button on the top right corner) is clicked and close the application when I click quit from my system tray context menu

To simplify what I want to do is I want something like Skype, which can exit through system tray options and hides to system try when clicked on the cross of window Following is my code,I have tried overriding cancel property to true on form closing event but it stops the closing process for system try option as well , How do I differentiate them .

`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Icon ico;




        private void Form1_Load(object sender, EventArgs e)
        {
              ico = notifyIcon1.Icon;
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void showFormToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void quitFormToolStripMenuItem_Click(object sender, EventArgs e)
        {

            this.Close();
        }

        private void Form1_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
                System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
                messageBoxCS.AppendFormat("{0} = {1}", "CloseReason", e.CloseReason);
                messageBoxCS.AppendLine();
                messageBoxCS.AppendFormat("{0} = {1}", "Cancel", e.Cancel);
                messageBoxCS.AppendLine();
                MessageBox.Show(messageBoxCS.ToString(), "FormClosing Event");

        }
    }
}
` 

Usually when I had to do this, I kept a statusflag to remember the call came from somewhere else to close me. So then in my closing handler I could check if I needed to close or hide...

bool bFormCloseRequested = false: //member of my Form

void MyCloseClick_Handler{object sender, eventArgs e)
{
    if(!bFormCloseRequested)
    {
        e.Cancel = true;
        this.hide();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM