1

我正在尝试创建一个可以继承的 NotifyIcon,以便我可以添加自己的属性/等。通过查看别人写的一个组件类,我已经取得了一些进展,如下图所示,并且可以将组件拖入表单中。老实说,我对自己在做什么一无所知,而且互联网上似乎根本没有任何有用的教程。

PrepareIcon您看到的方法中,弹出的消息框显示为空白,即使我尝试将值从设计器默认值更改为notifyIconInheritable1. 我在设计器中看到了 NotifyIcon 出现,所以我对它的工作原理完全感到困惑。

问题是; 这有什么问题或者我做错了什么,我是在浪费时间,根本不应该尝试这个吗?

namespace AwesomeNotifyIcon
{
    [DefaultProperty("Text"), DefaultEvent("Click"), Description("Displays an icon in the notification area, on the right side of the Windows taskbar, during run time")]
    public partial class NotifyIconInheritable : Component
    {
        private NotifyIcon notifyIcon;

        public NotifyIconInheritable()
        {
            //PrepareIcon();
            InitializeComponent();
        }

        public NotifyIconInheritable(IContainer container)
        {
            if (container != null)
            {
                container.Add(this);
            }
            PrepareIcon();
            InitializeComponent();
        }

        [Category("Appearance"), Description("The icon to associate with the balloon ToolTip."), DefaultValue(ToolTipIcon.None)]
        public ToolTipIcon BalloonTipIcon { get; set; }

        [Category("Appearance"), Description("The text to associate with the balloon ToolTip.")]
        public string BalloonTipText { get; set; }

        [Category("Appearance"), Description("The title of the balloon ToolTip.")]
        public string BalloonTipTitle { get; set; }

        [Category("Appearance"), Description("The icon to display in the system tray.")]
        public Icon Icon { get; set; }

        [Category("Appearance"), Description("The text that will be displayed when the mouse hovers over the icon.")]
        public string Text { get; set; }

        [Category("Behaviour"), Description("The shortcut menu to show when the user right-clicks the icon.")]
        public ContextMenuStrip ContextMenuStrip { get; set; }

        [Category("Behaviour"), Description("Determines whether the control is visible or hidden."), DefaultValue(false)]
        public bool Visible { get; set; }

        [Category("Data"), Description("User-defined data associated with the object.")]
        public object Tag { get; set; }

        [Category("Action"), Description("Occurs when the component is clicked.")]
        public event EventHandler Click;

        private void PrepareIcon()
        {
            notifyIcon = new NotifyIcon();
            notifyIcon.Dispose();
            MessageBox.Show(this.Text);

            if (Click != null)
                notifyIcon.Click += Click;
        }
    }
}

这是在设计器中看到的属性:

http://cl.ly/1vIF/content http://cl.ly/1vIF/content

4

1 回答 1

3

当您使用设计器添加控件时,它会生成如下所示的代码:

NotifyIconInheritable icon = new NotifyIconInheritable();
icon.Text = "Some text";
parent.Controls.Add(icon);

您可以看到在构造函数运行之后才设置您的属性。所以,当你打电话时PrepareIconText真的是空的。

其他建议:正如 Henk 所说,您真的不应该Dispose()在代码中此时调用。您也不应该显示来自构造函数的消息框,尽管希望这只是为了您的测试目的。最后,因为你是PrepareIcon从构造函数调用的,所以.Click总是null.

于 2010-08-09T09:11:42.510 回答