Shortest code to create modal dialog from stream

Let's say I have a thread running in the background to see if a URL is available. If no URL is available, the app should show a modal dialog. Things can't go on if the url doesn't work. If I just do a MessageBox.show from within the thread, this message box is not modal. ShowDialog won't work.

+1


source to share


4 answers


You can 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);    }

      



This will make it modal to the UI thread.

+4


source


You can try creating an event that fires from a background thread. Ask the main form to listen for the event, in which case it will disable the message box in the modal form. Although I like the approach suggested by ocdecio better.



+2


source


Thanks everyone. I solved the problem this way:

Topic:

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 he does his job.

+2


source


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 that wants to display a modal dialog in the form of a gui thread. The form method Invoke

takes a delegate and invokes that delegate on the gui form thread.

+1


source







All Articles