如何在多个表单之间使用1 notifyIcon?

时间:2011-12-18 22:06:40

标签: c# forms class notifyicon instantiation

我在项目的主要表单中添加了notifyIcon。我在项目中有其他形式,我希望能够使用notifyIcon,虽然这很难。在多个表单之间使用1 notifyIcon的最佳方法是什么?我读了一个关于不将它添加到表单中的线程,但是在它自己的类中实例化它对我来说没有任何意义。想法?

3 个答案:

答案 0 :(得分:4)

只需在主窗体上公开属性即可返回对NotifyIcon的引用。您甚至可以将其设置为静态,因为只有一个:

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;
}

其他类中的代码现在可以简单地使用MainForm.Notifier。

答案 1 :(得分:1)

在实现NotifyIcon的表单中创建一个公共静态变量:

public static NotifyIcon m_objNotifyIcon;

在表单加载分配表单NotifyIcon中:

m_objNotifyIcon = this.notifyIcon1;

全部设定。现在,您可以从项目中的任何位置访问通知图标

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

答案 2 :(得分:0)

即使您需要将MainForm指定给NotifyIcon控件,也不要看到在不同表单之间共享对象的任何问题。

让我们说,试着更清楚:

1。 MainForm启动并初始化NotifyIcon控件包装器类,让我们调用NotifyControlHolder

2。 NotifyControlHolder课程在您的UIShared中就像公共财产一样。

3。 UIShared单一类可以从应用程序的不同部分访问,可以绕过MainForm访问它并更改其状态。