Tim*_*Tim 9 c# user-interface winforms
我正在努力找到一种方法来创建我想要使用C#的Forms功能.
基本上,我想要一个具有指定超时时间的模式对话框.看起来这应该很容易,但我似乎无法让它发挥作用.
一旦我打电话this.ShowDialog(parent)
,程序流程就会停止,如果没有用户第一次点击按钮,我就无法关闭对话框.
我尝试使用BackgroundWorker类创建一个新线程,但我不能让它在另一个线程上关闭对话框.
我错过了一些明显的东西吗?
感谢您提供的任何见解.
Fre*_*örk 11
您需要在创建表单的线程上调用Close方法:
theDialogForm.BeginInvoke(new MethodInvoker(Close));
Run Code Online (Sandbox Code Playgroud)
adr*_*nks 11
使用System.Windows.Forms.Timer.将其Interval属性设置为超时,并将其Tick事件处理程序设置为关闭对话框.
partial class TimedModalForm : Form
{
private Timer timer;
public TimedModalForm()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 3000;
timer.Tick += CloseForm;
timer.Start();
}
private void CloseForm(object sender, EventArgs e)
{
timer.Stop();
timer.Dispose();
this.DialogResult = DialogResult.OK;
}
}
Run Code Online (Sandbox Code Playgroud)
计时器在UI线程上运行,因此可以安全地从tick事件处理程序关闭表单.