winforms Windows窗体在系统.线程.计时器事件后关闭

35g0bw71  于 2022-11-16  发布在  Windows
关注(0)|答案(1)|浏览(207)

我正在构建一个闹钟应用程序,并使用System.Threading.Timer。在计时器结束后,我希望显示usercontrol,以允许用户选择是唤醒还是休眠。在回调中添加新控件或窗体后,窗体刚刚关闭。

private void setTimerButton_Click(object sender, EventArgs e)
    {
        try
        {
            alarmDate = setAlarmDateTimePicker.Value - DateTime.Now;
            var alarmClock = new System.Threading.Timer(AlarmCallback, null, alarmDate, TimeSpan.Zero);
            addedAlarmTextBox.Text = setAlarmDateTimePicker.Text;
        }
        catch
        {}
        finally
        {
            setAlarmDateTimePicker.Value = DateTime.Now;
        }
    }
    private void AlarmCallback(object state)
    {
            this.Controls.Add(new AlarmBeepsForm());
    }

据我所知,它与线程有关,但我对编程很陌生,不明白哪里出了问题。我该如何更改代码以成功添加控件,还是应该使用另一种类型的计时器?

ttygqcqt

ttygqcqt1#

除非将Control.CheckForIllegalCrossThreadCalls设置为false,否则应调用Control.Invoke以切换到创建控制句柄的线程。

private void setTimerButton_Click(object sender, EventArgs e)
{
   try
   {
      alarmDate = setAlarmDateTimePicker.Value - DateTime.Now;
      var alarmClock = new System.Threading.Timer(AlarmCallback, null, alarmDate, TimeSpan.Zero);
      addedAlarmTextBox.Text = setAlarmDateTimePicker.Text;
   }
   catch
   {}
   finally
   {
      setAlarmDateTimePicker.Value = DateTime.Now;
   }
}
private void AlarmCallback(object state)
{
    this.Invoke(new Action(() => this.Controls.Add(new AlarmBeepsForm()));
}

相关问题