在新线程中显示模态对话框(最顶层)

时间:2011-11-03 13:00:03

标签: multithreading c#-4.0 modal-dialog

最顶层属性设置为true的模式对话框在新线程中显示时不会显示为最顶层。示例代码:

Thread thread = new Thread(KickOffForm);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

private void KickOffForm(object state)
{
    Thread.Sleep(5000); // Mimics logic that takes place before form is shown

    var form = new Form2();
    form.ShowDialog();
}

如果在线程开头实例化表单,则模式对话框显示为最顶层。示例代码:

Thread thread = new Thread(KickOffForm);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

private void KickOffForm(object state)
{
    var form = new Form2();

    Thread.Sleep(5000); // Mimics logic that takes place before form is shown

    form.ShowDialog();
}

上面的代码在exe启动时实例化的类中执行。

为什么表单在线程开头实例化时显示为最顶层,而不是稍后实例化?

2 个答案:

答案 0 :(得分:1)

表单只能是由它们创建和拥有的线程的模态。

如果要显示停止与主窗体交互的模式对话框,则必须在主UI线程上创建对话框。

必须如此,因为每个线程都运行它自己的消息循环。一个线程对另一个线程中的任何消息循环一无所知。

答案 1 :(得分:1)

也许你可以在一个正确的线程中调用对话框窗口:

   public partial class Form1 : Form
   {
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click( object sender, EventArgs e )
    {
        Thread thread = new Thread( KickOffForm );
        thread.SetApartmentState( ApartmentState.STA );
        thread.Start();

    }

    private void KickOffForm( object state )
    {
        var form = new Form2();

        Thread.Sleep( 5000 ); // Mimics logic that takes place before form is shown

        this.Invoke( (Action)(() => { form.ShowDialog(); }) );
    }
}