Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close modal dialog from external thread - C#

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.

like image 814
Tim Avatar asked Jun 17 '09 22:06

Tim


2 Answers

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

theDialogForm.BeginInvoke(new MethodInvoker(Close));
like image 53
Fredrik Mörk Avatar answered Sep 23 '22 12:09

Fredrik Mörk


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.

like image 30
adrianbanks Avatar answered Sep 22 '22 12:09

adrianbanks