我有两张表格
在表单1中只有一个Button
在表单2中,只有一个Web浏览器。
我想在webbrowser.DocumentText
跨线程操作无效:从中访问控制'webBrowser1' 一个线程,而不是它创建的线程。
public partial class Form1 : Form
{
CookieContainer cookies = new CookieContainer();
Form2 form2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(Dowork);
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
void Dowork()
{
try
{
Encoding charset = Encoding.GetEncoding("utf-8");
HttpWebRequest SMSRequset = (HttpWebRequest)WebRequest.Create("http://www.iam.ma/_layouts/SharepointFreeSms/EnvoyerSms.aspx");
SMSRequset.Method = "GET";
SMSRequset.CookieContainer = cookies;
HttpWebResponse SMSResponse = (HttpWebResponse)SMSRequset.GetResponse();
System.IO.StreamReader reader2 = new System.IO.StreamReader(SMSResponse.GetResponseStream(), charset);
form2.Show();
form2.Invoke((MethodInvoker)delegate
{
form2.webBrowser1.DocumentText = reader2.ReadToEnd();
});
}
catch (Exception EX)
{
MessageBox.Show(EX.Message);
}
}
}
我该怎么办?
错误在这里
form2.webBrowser1.DocumentText = reader2.ReadToEnd();
答案 0 :(得分:0)
通过调用更改要执行的所有代码:
form2.Show();
Encoding charset = Encoding.GetEncoding("utf-8");
HttpWebRequest SMSRequset = (HttpWebRequest)WebRequest.Create("http://www.iam.ma/_layouts/SharepointFreeSms/EnvoyerSms.aspx");
SMSRequset.Method = "GET";
SMSRequset.CookieContainer = cookies;
HttpWebResponse SMSResponse = (HttpWebResponse)SMSRequset.GetResponse();
System.IO.StreamReader reader2 = new System.IO.StreamReader(SMSResponse.GetResponseStream(), charset);
form2.webBrowser1.Invoke((MethodInvoker)delegate
{
form2.webBrowser1.DocumentText = reader2.ReadToEnd();
});