Change NotifyIcon in a separate form

I have a form (Form1) on which there is NotifyIcon. I have another form (Form2) with which I would like to change the NotifyIcon icon. Whenever I use this code, I get an additional icon that appears in the system tray instead of changing the current icon:

Form1 (ico - name NotifyIcon):

public string DisplayIcon { set { ico.Icon = new Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Alerts.Icons." + value)); } } 

Form2:

 Form1 form1 = new Form1(); form1.DisplayIcon = "on.ico"; 

I suspect this is due to creating a new instance of Form1 on Form2, but I'm not sure how to access the "DisplayIcon" without doing this. Thanks.

UDPATE: I am a bit confused about writing a custom property in form 2, it would be something like:

 public Form Form1 { set {value;} } 
+4
source share
2 answers

I assume that form1 at one point creates form2. At this point, you can pass the link form1 to form2 so that form2 can access the DisplayIcon property of form1.

So you get something like

 //Somewhere in the code of form1 public void btnShowFormTwoClick(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.Form1 = this; //if this isn't done within form1 code you wouldn't use this but the form1 instance variable form2.Show(); } //somewhere in the code of form2 public Form1 Form1 { get;set;} //To create the property where the form1 reference is storred. this.Form1.DisplayIcon = "on.ico"; 
+1
source

Your suspicion is true, you create a second instance of Form1, which leads to duplication of NotifyIcon.

You need a link to Form1 from Form2 to set the DisplayIcon property in the correct instance .

A possible solution is to pass the link from Form1 to Form2 when creating Form2 (I assume that you are creating Form2 from Form1).

For instance:

 Form2 form2 = new Form2(); form2.Form1 = this; // Form1 is custom property on Form2 that you need to add form2.Show(); 

In Form2, a custom property will be defined as:

  //Note the type is Form1, in order to get to your public DisplayIcon property. public Form1 Form1 { get;set;} 
+1
source

All Articles