在自定义工具控件上引发自定义事件

时间:2014-06-25 18:36:33

标签: c# winforms

我正在尝试测试一些东西并且无法弄明白。我有一个自定义用户控件,我使用SDK插件创建了Microsoft VS 2012.我对事件或代表来说还不是很好。

我的愿望是当启用(或禁用)此控件时,它会引发一个事件以启动(或停止)timer1。当此timer1达到指定时间时,它将调用创建tcp客户端并执行服务器请求的方法。

这是我的用户控件中的代码,该代码托管在主窗体上。

    public custom_cont()
    {
        InitializeComponent();

        timer1.Tick += new EventHandler(timer1_Tick);
        EnabledChanged += new EventHandler(OnEnabledChanged); 
    }

    int timer1Count;

     public void timer1_Tick(object sender, System.EventArgs e)
    {
        timer1Count++;
        if (timer1Count == TickTimer) //TickTimer is a property I can control from my usercontrol hosted project.
            ProcessUpload(); // Tcp-client creation... takes cares of send and receive response
    }


    public void OnEnabledChanged(object sender, System.EventArgs e)
    {
        if (Enabled)
            timer1.Start();
        else
            timer1.Stop();
    }

在我的主表单上,我在controlList中包含了许多同一类型的自定义控件List<T>,当我启用它们时:

foreach (var control in controlList)
        {
                control.Enabled = true;
        }

什么都没发生。用户控件应根据我ProcessUpload()中的连接状态更改颜色。当我通过ProcessUpload()直接从主表单中调用control.ProcessUpload()时,它可以正常工作。我把它们链接到我的控制表的事件部分。如何使enable和timing事件工作,以便我不需要显式调用控件中包含的方法?理想情况下,他们会根据时间间隔提高。

1 个答案:

答案 0 :(得分:2)

&#39; EnabledChanged&#39;设置Enabled = true时不会触发事件,除非当前禁用该控件(因为没有更改)。因此,在添加事件处理程序之前,请将其设置为false:

this.Enabled = false;
this.EnabledChanged += new EventHandler(OnEnabledChanged); 
相关问题