Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

c# - In a winforms application, how can you run a messagebox from a background worker that must always be in the foreground?

Right now, I'm using a background worker thread to check something every so often and if the conditions are met a messagebox is generated.

I didn't notice for awhile that because I'm calling the messagebox in the background worker I lose the usual messagebox behavior of not letting the user click back on the main form before they click yes/no/cancel on the messagebox.

So, is there some option on the messagebox to keep it in the foreground always? Or is it possible to send a message from the background worker to the main form so I can generate the messagebox from there? Is there another way?

Thanks

Isaac

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A background worker is a different thread than your windows form. Therefor you need to let your background worker somehow return information back to the main thread. In the example below, I use the reportProgress functionality of the backgroundworker, as the event is triggered on the windows form thread.

public partial class Form1 : Form
{
    enum states
    {
        Message1,
        Message2
    }
    BackgroundWorker worker;

    public Form1()
    {
        InitializeComponent();
        worker = new BackgroundWorker();
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        worker.WorkerReportsProgress = true;
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Fake some work, report progress
        worker.ReportProgress(0, states.Message1);
    }

    void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        states state = (states)e.UserState;
        if (state == states.Message1) MessageBox.Show("This should hold the form");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        worker.RunWorkerAsync();
    }

}

Note: The background worker will NOT halt at reportProgress. If you want your bgworker to wait until the mbox is pressed, you need to make a halt something manually for it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...