tags:

views:

42

answers:

2

I'm developing a Windows Form application in C#. I have a main form called MainWindow and a NotifyIcon object called notifyIcon that belongs to the MainWindow class.

What is the best way for me to use notifyIcon from other classes?

I know that, without an instance, I can only access public static members of the class, but if I set the notifyIcon as public static, it stops working on MainWindow.

Any ideas?

+2  A: 

If it's the same application you can use

Application.OpenForms

to retrieve opened forms.

This property returns a FormCollection, you can get the form instance from there. More info here.

If it's not the same assembly see this.

BrunoLM
I tried this, but when I do 'Form main = Application.OpenForms["MainWindow"];', I'm still unable to call a public method of MainWindow.
Jr. Hames
@Jr. You are missing a cast. It's not `Form main`, it should be `var main = Application.OpenForms["MainWindow"] as YourFormThatInheritsFromForm;`. `Form` doesn't know your method, only the child class knows it.
BrunoLM
It works. Thank you.
Jr. Hames
A: 

You can expose a public method on the form. This method can internally call the methods on notifyicon

Nilesh Gule
I think for accessing a public method, you need to create a object of that form, and if you create a new object of that form, then there will be 2 notify icons.
Searock