如何安全地跨窗体调用Timer控件 从一个窗体调用控制另外一个窗体的控件

具体的情况是Form1中有一个Timer2时钟,Timer2时钟事件弹出Warning窗体,点击Warning窗体上面的按钮,重新激活一下Form1中的Timer2。从而实现了从一个窗体调用另外一个窗体的控件的目的。

Timer2时钟每次都执行一次就会停止。

首先在Form1.cs中加入代码,弹出warning窗体:

Warning warning = Warning.GetInstance();
                warning.Owner = this;
                warning.ShowDialog()

然后在Warning.cs中的Button事件中,加入代码:

private void button1_Click(object sender, EventArgs e)
		{
            Form1 f1 = (Form1)this.Owner;
            f1.timer2.Enabled=true;
            this.Hide();          
          
			
		}

窗体Warning的实例并没有销毁,而是this.Hide() 隐藏掉。Button触发Form1中Timer2开启。

而防止Warning重复实例化,Warning.cs中,在 Waring的构造函数中加入:

private static Warning instance;
        public static Warning GetInstance()
        {
            if (instance == null || instance.IsDisposed == true)//加一个IsDisposed判断,防止对象被释放了而无法访问
            {
                instance = new Warning();
                instance.Icon = Properties.Resources.DataView;
            }
            return instance;
        }
posted @ 2015-09-04 18:40  海尔卡特  阅读(1033)  评论(0编辑  收藏  举报