How can I use 1 notifyIcon between multiple forms?

为君一笑 提交于 2019-12-24 23:02:42

问题


I have a notifyIcon added to my main form of a project. I have other forms in the project that I want to be able to use the notifyIcon though which is proving difficult. What would be the best way to use 1 notifyIcon between multiple forms? I read a thread about not adding it to a form but instantiating it in its own class which made no sense to me. Thoughts?


回答1:


Just expose a property on your main form to return a reference to the NotifyIcon. You can even make it static since there is only ever one:

public partial class MainForm : Form {
    public MainForm() {
        InitializeComponent();
        notifier = this.notifyIcon1;
        this.FormClosed += delegate { notifier = null; };
    }

    public static NotifyIcon Notifier { get { return notifier; } }

    private static NotifyIcon notifier;
}

Code in other classes can now simply use MainForm.Notifier.




回答2:


Create a public static variable in the Form where NotifyIcon is implemented:

public static NotifyIcon m_objNotifyIcon;

in form load assign forms NotifyIcon:

m_objNotifyIcon = this.notifyIcon1;

all set. Now you can access the notify icon from anywhere in the project

Forms.MainScreen.m_objNotifyIcon.ShowBalloonTip(2000, "Title", "Message", ToolTipIcon.Info);



回答3:


Even if you need to assign MainForm to NotifyIcon control, don't see any problem about sharing it's object between different forms.

Let's say, to try to be more clear:

1. MainForm starts and initializes NotifyIcon control wrapper class, let's call NotifyControlHolder.

2. That NotifyControlHolder class stands in your UIShared like a public property.

3. UIShared singletone class is accesible from differnt parts of your application, which can access it and change it's state, bypassing the MainForm.



来源:https://stackoverflow.com/questions/8555204/how-can-i-use-1-notifyicon-between-multiple-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!