tags:

views:

507

answers:

4

Hello,

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.

A: 

you can Invoke the close from your background thread

Sam Saffron
+4  A: 

You will need to call the Close method on the thread that created the form:

theDialogForm.BeginInvoke(new MethodInvoker(Close));
Fredrik Mörk
+7  A: 

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.

adrianbanks
A: 

If you really just want a modal dialog then I found this to be the best solution by far: http://www.codeproject.com/KB/miscctrl/CsMsgBoxTimeOut.aspx (read the comments section for a small modification).

If you want to display your own form modally, then the solution from adrianbanks is best.

Dommer