C# calling form.show() from another thread

后端 未结 4 1867
野性不改
野性不改 2020-12-16 10:48

if I call form.show() on a WinForms object from another thread, the form will throw an exception. Is where any way I can add a new, visible form to the main ap

4条回答
  •  [愿得一人]
    2020-12-16 11:30

    The best way by my experience:

    var ac = (ReportPre)Application.OpenForms["ReportPre"];
    Thread shower = new Thread(new ThreadStart(() =>
        {
            if (ac == null)
            {                
                this.Invoke((MethodInvoker)delegate () {
                    ac = new ReportPre();
                    ac.Show();
                });       
            }
            else
            {
                this.Invoke((MethodInvoker)delegate
                {
                    pictureBox1.Visible = true;
                });
                if (ac.InvokeRequired)
                {
                    ac.Invoke(new MethodInvoker(delegate {
                        ac.Hide();
                        ac.Show();
                    }));                          
                }
            }
        }));
    shower.Start();
    

提交回复
热议问题