Hao Wooi Lim
Hao Wooi Lim

Reputation:

Shortest code to spawn a modal dialog box from a thread

Say I have a thread that keeps running in the background to figure if a URL is accessible. If the URL is not accessible, the application need to show a modal dialog box. Things cannot go on if the URL is down. If I simply do a MessageBox.show from inside the thread, that message box will not be modal. ShowDialog won't work either.

Upvotes: 1

Views: 3539

Answers (4)

Hao Wooi Lim
Hao Wooi Lim

Reputation:

Thanks everyone. I solved the problem this way:

The thread:

private Thread tCheckURL;

// ...

tCheckURL = new Thread(delegate()
{
    while (true)
    {
        if (CheckUrl("http://www.yahoo.com") == false)
        {
            form1.Invoke(form1.myDelegate);
        }
    }
});
tCheckURL.Start();

Inside Form1:

public delegate void AddListItem();
public AddListItem myDelegate;

Form1()
{
    //...
    myDelegate = new AddListItem(ShowURLError);
}
public void ShowURLError()
{
    MessageBox.Show("The site is down");
}

Not sure if this is the shortest way to do it.. but it gets the job done.

Upvotes: 2

yfeldblum
yfeldblum

Reputation: 65445

public class FooForm : Form {

    public static void Main() {
        Application.Run(new FooForm());
    }

    public FooForm() {
        new Thread(new Action(delegate {
            Invoke(new Action(delegate {
                MessageBox.Show("FooMessage");
            }));
        })).Start();
    }

}

This program creates a form window, and immediately creates another non-gui thread which wants to pop up a modal dialog window on the form's gui thread. The form's Invoke method takes a delegate and invokes that delegate on the form's gui thread.

Upvotes: 1

Jason Down
Jason Down

Reputation: 22181

You could try creating an event that fires from the background thread. Have the main form listen for the event in which case it would fire off the messagebox in modal form. Though I like the approach suggested by ocdecio better.

Upvotes: 2

Otávio Décio
Otávio Décio

Reputation: 74290

You may want to use Control.Invoke (or this.Invoke)

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
      this.Invoke(new MessageBoxDelegate(ShowMessage), "Title", "MEssage", MessageBoxButtons.OK, MessageBoxIcon.Information);    }

That will make it modal to the UI thread.

Upvotes: 4

Related Questions