Question

I plan to use this method to display a notify icon so it can be accessed between the main form and child forms (found from another SO post)

public partial class MainForm : Form {
    public MainForm() {
        InitializeComponent();
        notifier = this.notifyIcon1;
        this.FormClosed += delegate { notifier = null; };
    }

    public static NotifyIcon Notifier { get { return notifier; } }

    private static NotifyIcon notifier;
}
  1. Is it necessary to add the FormClosed delegate? I would think that when the form everything else gets destroyed and freed up?

Edit: For clarification - I can confirm that using the code without the delegate above, when i close the form the system tray icon does disappear, also I did use the VS UI to drag/drop a NotifyIcon from toolbox so designer is handling initialization for me and I am using the constructor like above to access it.

Était-ce utile?

La solution

If the notify icon is logically tied to this instance of the form then you shouldn't have it be a static field. Marking it as static is done to specifically say that it's not tied to one instance, but rather is shared between all instances.

I would think that when the form everything else gets destroyed and freed up?

If it were instance data it would be, but because it's static, and therefore not tied to the instance, it will not be cleaned up when the form goes away.

Of course, if this is the main form (and not a misnomer) then the entire application will end when the form closes, which will clean up everything regardless, static or not.

Autres conseils

You need to set

nutifier.Visible = false;
notifier = null;

on closing. If not, the icon stays after the application was closed

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top