Fuzz Evans
Fuzz Evans

Reputation: 2943

How can I use 1 notifyIcon between multiple forms?

I have a notifyIcon added to my main form of a project. I have other forms in the project that I want to be able to use the notifyIcon though which is proving difficult. What would be the best way to use 1 notifyIcon between multiple forms? I read a thread about not adding it to a form but instantiating it in its own class which made no sense to me. Thoughts?

Upvotes: 1

Views: 2359

Answers (3)

Irfon
Irfon

Reputation: 11

Create a public static variable in the Form where NotifyIcon is implemented:

public static NotifyIcon m_objNotifyIcon;

in form load assign forms NotifyIcon:

m_objNotifyIcon = this.notifyIcon1;

all set. Now you can access the notify icon from anywhere in the project

Forms.MainScreen.m_objNotifyIcon.ShowBalloonTip(2000, "Title", "Message", ToolTipIcon.Info);

Upvotes: 1

Tigran
Tigran

Reputation: 62248

Even if you need to assign MainForm to NotifyIcon control, don't see any problem about sharing it's object between different forms.

Let's say, to try to be more clear:

1. MainForm starts and initializes NotifyIcon control wrapper class, let's call NotifyControlHolder.

2. That NotifyControlHolder class stands in your UIShared like a public property.

3. UIShared singletone class is accesible from differnt parts of your application, which can access it and change it's state, bypassing the MainForm.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941257

Just expose a property on your main form to return a reference to the NotifyIcon. You can even make it static since there is only ever one:

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;
}

Code in other classes can now simply use MainForm.Notifier.

Upvotes: 5

Related Questions