I am struggling to find a way to create the Forms functionality that I want using C#.
Basically, I want to have a modal dialog box that has a specified timeout period. It seems like this should be easy to do, but I can't seem to get it to work.
Once I call this.ShowDialog(parent)
, the program flow stops, and I have no way of closing the dialog without the user first clicking a button.
I tried creating a new thread using the BackgroundWorker class, but I can't get it to close the dialog on a different thread.
Am I missing something obvious here?
Thanks for any insight you can provide.
You will need to call the Close method on the thread that created the form:
theDialogForm.BeginInvoke(new MethodInvoker(Close));
Use a System.Windows.Forms.Timer. Set its Interval property to be your timeout and its Tick event handler to close the dialog.
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;
}
}
The timer runs on the UI thread so it is safe to close the form from the tick event handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With