在线程c#中打开窗体(MDI)

时间:2016-11-16 07:34:31

标签: c# .net multithreading winforms

我正在使用MDI表单,现在点击MDI表单中的菜单,我在<ul> <li><b>title</b>description</li> <li><b>title</b>description</li> <li>description without title</li> <li><b>title</b>description</li> </ul>(面板)中打开其他表单,这可以作为表单的容器。

我在想的是,当应用程序加载时,它会打开一个默认表单。 此时我想打开所有表单,但是一次打开所有表单会妨碍性能,其他表单打开应该在不同的线程中运行。然后,如果所有表单都已打开,则用户可以快速切换表单。

PnlView

抛出异常,

跨线程操作无效:从

上创建的线程以外的线程访问控件''

获得以下异常,  No Overload'OpenForm'匹配委托MethodInvoker

   private bool IsFormAlreadyOpen(ControlItem _item)
    {
       bool reutrnValue = false;
       foreach (Control ctrl in PnlView.Controls)
       {
          if (ctrl.Name.ToLower() == _item.Control.Name.ToLower())
          {
             reutrnValue = true;
             break;
          }
       }
       return reutrnValue;
    }


This is the function which checks if form is already opened or not. So this will get all the forms open and will just bring that form to front.

Can anyone helps me with opening form in thread so that it will not impact the performance.  
I hope this makes sense.

---------------------------------------------------------------------

     private void MdiForm1_Load(object sender, EventArgs e)
    {
  OpenFirstForm(); //This ospens a default form, form name frmDefault
         bw.WorkerReportsProgress = true;
                bw.WorkerSupportsCancellation = true;
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                bw.RunWorkerAsync();
            }

            private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                //this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
            }

            private void bw_DoWork(object sender, DoWorkEventArgs e)
            {
                BackgroundWorker worker = sender as BackgroundWorker;

                for (int i = 1; (i <= 2); i++)
                {
                    if ((worker.CancellationPending == true))
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        // Perform a time consuming operation and report progress.
                        //System.Threading.Thread.Sleep(500);
                       OpenForms(form1);
                       OpenForms(form2);
                        worker.ReportProgress((i * 10));
                    }
                }
            }

1 个答案:

答案 0 :(得分:1)

问题是您正在尝试访问从另一个线程在一个线程中实例化的控件。使用以下代码段解决您手头的问题:

formData

希望这有帮助。