C# – Windows Form: closing, but not closing

cwinforms

I have a strange problem with my Windows Form Application (C#). I have a form (Form1) with a NotifyIcon and a another form (Form2) in my project. Form1 has some code that basically does some XML parsing and adds a bunch of LinkLabels onto Form2. This all work fine.

On the NotifyIcon, I have a ContextMenu MenuItem (called "Refresh") with an EventHandler to, basically, run through the XML parsing on command. I also have, on the NotifyIcon, a MouseDoubleClick command which, when the system tray icon is double-clicked, it open up Form2 (using ShowDialog()) to display the link of LinkLabels. This also works fine.

I have a Button Control on Form2 (called "Close"), that is using this EventHandler code:

private void btnClose_Click(object sender, EventArgs e)
{
    this.Close();
}

to close Form2. This also works fine.

However, depending on how many times the "Refresh" ContextMenu MenuItem, on Form1's NotifyIcon, is hit, this is how many time the "Close" Button Control on Form2 must be pressed before Form2 closes. For example, if a user hits the "Refresh" MenuItem on Form1 three times, they will have to hit the "Close" Button Control on Form2 three times to it. It's almost like Form2 visibly closes, but the code doesn't seem to recognize that it is closed.

I'm new to Windows Form's development, so maybe it's a lifecycle thing I'm not aware of. Any help would be appreciated.

EDIT. I'll try to post the appropriate code:

//NotifyIcon Form (Form1)
//ico is the ID of the NotifyIcon
public partial class TrayIcon : Form
{
    Message msg = new Message(); //Form2
    ContextMenu contextMenu = new ContextMenu();

    public TrayIcon()
    {
        InitializeComponent();
    }

    private void TrayIcon_Load(object sender, EventArgs e)
    {
        contextMenu.MenuItems.Clear();
        contextMenu.MenuItems.Add(0, new MenuItem("Refresh", new System.EventHandler(ico_Refresh)));

        ico.DoubleClick += new MouseEventHandler(ico_ShowMsg);

        DoXmlParsing();
    }

    private void ico_Refresh(object Sender, EventArgs e)
    {
        TrayIcon_Load(null, null);
    }

    private void ico_ShowMsg(object Sender, MouseEventHandler e)
    {
        if (msg.Visible == false)
            msg.ShowDialog();
    }
}

On Form2 (Message) I have a Button with this Click handler code:

private void btnClose_Click(object sender, EventArgs e)
{
    this.Close();

    //I have also tried:
    if (this.Visible)
        this.Hide();
}

Best Answer

I think this line is the problem:

ico.DoubleClick += new MouseEventHandler(ico_ShowMsg);

You keep adding more event handlers to the double click, but never removing them (because TrayIcon_Load is called in ico_Refresh.

After you close the dialog, the .ShowDialog() is called again however many times this event handler has been added.

Related Topic