次のコードでは、「クロス スレッド操作」の例外が発生します。「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"]);
}));
}
}
}