从外部线程关闭模态对话框 - C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1009913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:27:54  来源:igfitidea点击:

Close modal dialog from external thread - C#

c#winformsuser-interface

提问by Tim

I am struggling to find a way to create the Forms functionality that I want using C#.

我正在努力寻找一种方法来使用 C# 创建我想要的表单功能。

Basically, I want to have a modal dialog box that has a specified timeout period. It seems like this should be easy to do, but I can't seem to get it to work.

基本上,我想要一个具有指定超时期限的模式对话框。看起来这应该很容易做到,但我似乎无法让它发挥作用。

Once I call this.ShowDialog(parent), the program flow stops, and I have no way of closing the dialog without the user first clicking a button.

一旦我调用this.ShowDialog(parent),程序流就会停止,如果没有用户首先单击按钮,我将无法关闭对话框。

I tried creating a new thread using the BackgroundWorker class, but I can't get it to close the dialog on a different thread.

我尝试使用 BackgroundWorker 类创建一个新线程,但我无法让它关闭其他线程上的对话框。

Am I missing something obvious here?

我在这里遗漏了一些明显的东西吗?

Thanks for any insight you can provide.

感谢您提供的任何见解。

采纳答案by adrianbanks

Use a System.Windows.Forms.Timer. Set its Intervalproperty to be your timeout and its Tickevent handler to close the dialog.

使用System.Windows.Forms.Timer。将其Interval属性设置为您的超时时间,并将其Tick事件处理程序设置为关闭对话框。

partial class TimedModalForm : Form
{
    private Timer timer;

    public TimedModalForm()
    {
        InitializeComponent();

        timer = new Timer();
        timer.Interval = 3000;
        timer.Tick += CloseForm;
        timer.Start();
    }

    private void CloseForm(object sender, EventArgs e)
    {
        timer.Stop();
        timer.Dispose();
        this.DialogResult = DialogResult.OK;
    }
}

The timer runs on the UI thread so it is safe to close the form from the tick event handler.

计时器在 UI 线程上运行,因此可以安全地从刻度事件处理程序关闭表单。

回答by Sam Saffron

you can Invokethe close from your background thread

您可以从后台线程调用关闭

回答by Fredrik M?rk

You will need to call the Close method on the thread that created the form:

您需要在创建表单的线程上调用 Close 方法:

theDialogForm.BeginInvoke(new MethodInvoker(Close));

回答by Tom Chantler

If you really just want a modal dialog then I found this to be the best solution by far: http://www.codeproject.com/KB/miscctrl/CsMsgBoxTimeOut.aspx(read the comments section for a small modification).

如果你真的只想要一个模态对话框,那么我发现这是迄今为止最好的解决方案:http: //www.codeproject.com/KB/miscctrl/CsMsgBoxTimeOut.aspx(阅读评论部分进行小修改)。

If you want to display your own form modally, then the solution from adrianbanks is best.

如果您想以模态方式显示自己的表单,那么 adrianbanks 的解决方案是最好的。