In a winforms application, how can you start a mailbox from a desktop background that should always be in the foreground?

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

For a while, I did not notice that since I call the message in the background worker, I lose the usual behavior in the messages, preventing the user from clicking on the main form before they click the yes / no / cancel button in the message window.

So, is there any option in the message box to always keep it in the foreground? Or can I send a message from a background worker to the main form so that I can create a mailbox there? Is there another way?

thanks

Isaac

+7
source share
2 answers

A background worker is a different thread than the shape of your window. Therefore, you need your background worker to somehow return information back to the main stream. In the example below, I use the reportProgress function for the background worker, since the event is fired in the window 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 stop at reportProgress. If you want your bgworker to wait until mbox is pressed, you need to do something manually for it.

+9
source

You can use the Invoke method of class Form1 to invoke this form user interface stream.

 this.Invoke(() => MessageBox.Show("Hi")); 
+2
source

All Articles