Reputation: 3578
I have a form (Form1) that has a NotifyIcon on it. I have another form (Form2) that I would like to change the NotifyIcon's icon from. Whenever I use this code, I get an extra icon that shows up in the system tray, instead of changing the current icon:
Form1 (ico is the name of the 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 is has something to do with creating a new instance of Form1 on Form2, but I'm not sure how to access "DisplayIcon" without doing this. Thanks.
UDPATE: I'm a little confused on writing the custom property on Form 2, would it be something like:
public Form Form1
{
set {value;}
}
Upvotes: 4
Views: 1079
Reputation: 116827
Your suspicion is correct, you are creating a second instance of Form1 which results in a duplicate NotifyIcon.
You need a reference to Form1 from Form2 in order to set the DisplayIcon property on the correct instance.
A possible solution is to pass the reference from Form1 to Form2 when creating Form2 (I assume you create Form2 from Form1).
For example:
Form2 form2 = new Form2();
form2.Form1 = this; // Form1 is custom property on Form2 that you need to add
form2.Show();
On Form2 the custom property would be defined as:
//Note the type is Form1, in order to get to your public DisplayIcon property.
public Form1 Form1 { get;set;}
Upvotes: 1
Reputation: 4595
I assume form1 at one point creates form2. At that point you can pass a reference of form1 to form2 so form2 can access the DisplayIcon property of form1.
So you would end up with 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";
Upvotes: 1