以下代码给出了“跨线程操作”异常。只是因为“form2.ResumeLayout(false)”。如果这句话被评论了,我就看不到表单中的浏览器了。我知道ResumeLayout(false)的必要性,但有解决方案吗?
namespace WindowsFormsApplication1
{
public partial class Form1: Form
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{ if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); }
private System.Windows.Forms.Button button1;
public Form1()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(64, 47);
this.button1.Text = this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.Click += new System.EventHandler(this.button1_Click);
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.button1);
this.Text = this.Name = "Form1";
this.ResumeLayout(false);
}
private void button1_Click(object sender, EventArgs e)
{
Class1 clss = new Class1();
clss.startme();
}
}
class Class1
{
public void startme()
{
Thread thread = new Thread(new ParameterizedThreadStart(Run));
thread.SetApartmentState(ApartmentState.STA);
thread.Start(null);
}
private void Run(object j)
{
WebBrowser webBrowser1 = new WebBrowser();
webBrowser1.Dock = DockStyle.Fill;
webBrowser1.Navigate("https://dshift.sharepoint.com");
Form form2 = new Form();
form2.SuspendLayout();
form2.Controls.Add(webBrowser1);
form2.ResumeLayout(false);
Application.OpenForms["Form1"].Invoke(new MethodInvoker(delegate
{
form2.ShowDialog(Application.OpenForms["Form1"]);
}));
}
}
}