在Winforms应用程序中,如何从必须始终位于前台的后台工作程序运行消息框? [英] In a winforms application, how can you run a messagebox from a background worker that must always be in the foreground?

查看:34
本文介绍了在Winforms应用程序中,如何从必须始终位于前台的后台工作程序运行消息框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在使用后台工作线程每隔一段时间检查一次内容,如果满足条件,则会生成一个消息框.

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?

谢谢

以撒

推荐答案

后台工作程序是与Windows窗体不同的线程.因此,您需要让后台工作人员以某种方式将信息返回到主线程.在下面的示例中,由于事件是在Windows窗体线程上触发的,因此我使用了后台工作程序的reportProgress功能.

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();
    }

}

注意:后台工作程序不会在reportProgress处停止.如果要让bgworker等待直到按下mbox,则需要为此手动停止操作.

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.

这篇关于在Winforms应用程序中,如何从必须始终位于前台的后台工作程序运行消息框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆