c# – 从另一个线程关闭表单
发布时间:2020-12-15 21:44:55 所属栏目:百科 来源:网络整理
导读:我有一个管理器类,它使用ShowDialog函数启动一个Form.现在,我正在启动一个事件(如计时器),并希望管理员在计时器到期时关闭表单. 我用了2个班: namespace ConsoleApplication3{class Manager{ Timer UpdTimer = null; readonly int REFRESH_STATUS_TIME_INTE
我有一个管理器类,它使用ShowDialog函数启动一个Form.现在,我正在启动一个事件(如计时器),并希望管理员在计时器到期时关闭表单.
我用了2个班: namespace ConsoleApplication3 { class Manager { Timer UpdTimer = null; readonly int REFRESH_STATUS_TIME_INTERVAL = 5000; Form1 form1; public Manager() { } public void ManageTheForms() { UpdTimer = new Timer(REFRESH_STATUS_TIME_INTERVAL); // start updating timer //UpdTimer.Interval = REFRESH_STATUS_TIME_INTERVAL; UpdTimer.Elapsed += new ElapsedEventHandler(PriorityUpdTimer_Elapsed); UpdTimer.Start(); form1 = new Form1(); form1.ShowDialog(); } public void PriorityUpdTimer_Elapsed(object source,ElapsedEventArgs e) { UpdTimer = null; form1.closeFormFromAnotherThread(); } } } Form1类: namespace ConsoleApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_FormClosing(object sender,FormClosingEventArgs e) { } delegate void CloseFormFromAnotherThread(); public void closeFormFromAnotherThread() { if (this.InvokeRequired) { CloseFormFromAnotherThread del = new CloseFormFromAnotherThread(closeFormFromAnotherThread); this.Invoke(del,new object[] { }); } else { this.Close(); } } } } 解决方法
如果我是对的,你想在计时器停止时关闭表格.
这就是我这样做的方式: System.Threading.Timer formTimer; 我使用布尔值来查看计时器是否仍处于活动状态 public Boolean active { get; set; } 创建此功能: public void timerControl() { if (!active) formTimer = new System.Threading.Timer(new TimerCallback(TimerProc)); try { formTimer.Change(REFRESH_STATUS_TIME_INTERVAL,0); } catch {} active = true; } 要完成计时器,您需要使用TimerProc函数,该函数在创建新计时器时调用: private void TimerProc(object state) { System.Threading.Timer t = (System.Threading.Timer)state; t.Dispose(); try { CloseScreen(); } catch{} } 为了让我更容易编程,我创建了CloseScreen()函数: public void CloseScreen() { if (InvokeRequired) { this.Invoke(new Action(CloseScreen),new object[] { }); return; } active = false; Close(); } 将所有这些函数放在表单类中,然后使用timerControl激活计时器.您可以选择从Manager类访问它:Form1.TimerControl();或者把它放在一个事件处理程序中,成功! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |