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

在单独的窗体上更改notifyicon

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

    我有一个窗体(Form1),上面有一个NotifyIcon。我有另一个表单(表单2),我想从中更改NotifyIcon的图标。每当我使用此代码时,系统托盘中会显示一个额外的图标,而不是更改当前图标:

    表1(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";
    

    我怀疑与在Form2上创建新的Form1实例有关,但我不知道如何在不这样做的情况下访问“DisplayIcon”。谢谢。

    udpate:在表单2上编写自定义属性时,我有点困惑,是不是应该是:

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

    我假设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    15 年前

    您的怀疑是正确的,您正在创建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();
    

    在Form2上,自定义属性将定义为:

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