代码之家  ›  专栏  ›  技术社区  ›  Kris B

在单独的表单上更改NotifyIcon

  •  4
  • Kris B  · 技术社区  · 16 年前

    我有一个表单(Form1),上面有一个NotifyIcon。我有另一个表格(Form2),我想从中更改NotifyIcon的图标。每当我使用这段代码时,我都会在系统托盘中看到一个额外的图标,而不是更改当前的图标:

    Form1(ico是NotifyIcon的名称):

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

    表格2:

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

    public Form Form1
    {
        set {value;}
    }
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   olle    16 年前

    我假设form1在某一点上创建了form2。此时,您可以将form1的引用传递给form2,以便form2可以访问form1的DisplayIcon属性。

    所以你最终会得到这样的结果

    //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";
    
        2
  •  1
  •   Philip Fourie    16 年前

    您的怀疑是正确的,您正在创建Form1的第二个实例,这会导致重复的NotifyIcon。

    您需要从Form2引用Form1,以便在 正确实例 .

    一种可能的解决方案是在创建Form2时将引用从Form1传递到Form2(我假设您是从Form1创建Form2的)。

    例如:

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

     //Note the type is Form1, in order to get to your public DisplayIcon property. 
     public Form1 Form1 { get;set;} 
    
    推荐文章