Instantiation Question Creating Too Many Objects

  • Thread starter Thread starter jm
  • Start date Start date
J

jm

I have a Form1 and two class files.

In the first class, I call the second class. The second class
references the Form1 notifyicon and changes the icon. It works.

The problems is, however, that because I am doing:

Form1 f = new Form1();

f.notifyIcon.Icon = myIcon;

everytime this second class method is called I get an extra icon in
the system tray. I realize this is because I am creating a new Form1
object with its own set of icons, etc.

My problem is that I do not know how to simply use the same Form1 that
I started out with, especially, since I started out on Form1, went to
class one, and then finally called something out of class two.

I know it is basic, sorry. Thank you for any help.
 
Something like below should work...


Class 1
(
Form1 f = new Form1();
Class2 foo = new Class2();
f.notifyIcon.Icon = foo.YourMethod();

)
Class2
(

public Icon YourMethod()
{

return icon;
}

)
 
Scott said:
Something like below should work...


Class 1
(
Form1 f = new Form1();
Class2 foo = new Class2();
f.notifyIcon.Icon = foo.YourMethod();

)
[...snip...]

This would work if called from Class1 presuming you are creating the Form1
instance from inside the Class1 instance, but not if any work inside a
Class2 method should cause the notifyIcon to change.

You should pass a reference to the original instance of Form1 to the Class1
instance and on to the Class2 instance, for example with a public property
of Class1 and (!) Class2. This requires the Form1 instance to be known at
Class1 instances creation time:

public class Form1
{
private void Form1Method()
{
// whatever comes before...
Class1 myClass1Instance = new Class1();
myClass1Instance formToManipulate = this;
}
}

public class Class1
{
private Form1 originatingForm;

public Form1 formToManipulate
{
get { return originatingForm; }
set { originatingForm = value; }
}

private void someMethod()
{
Class2 myClass2Instance = new Class2();
myClass2Instance formToManipulateNotifyIcon = this.formToManipulate;
}
}

public class Class2
{
private Form1 formForNotifyIcon;

public Form1 formToManipulateNotifyIcon
{
get { return formForNotifyIcon; }
set { formForNotifyIcon = value; }
}

private void otherMethod()
{
Icon myIcon = this.getNewIconFromSomewhere();
this.formToManipulateNotifyIcon.notifyIcon.Icon = myIcon;
}
}

As an alternative, you can make the Class1 instance known to the Class2
instance and call something like

this.originatingClass1Instance.formToManipulate.notifyIcon.Icon = myIcon;
 
Back
Top