I am trying to create a multi-threaded application that creates WebBrowsers and does specific things to each one. When I tried my code from the main thread it worked great, However, When I changed the code to run from a thread, the code runs fine until InvokeMember("click")
is called and nothing happens. InvokeMember()
isn't executed and the button click doesn't take place. Here is my code:
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(Work);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
[STAThread]
void Work()
{
WebBrowser wb = new WebBrowser();
wb.ScriptErrorsSuppressed = false;
wb.Visible = true;
wb.Navigate("http://website.com");
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
//updateText("Loaded");
wb.Document.GetElementById("F1").SetAttribute("Value", "Test");
wb.Document.GetElementById("F2").SetAttribute("Value", "Saracostaz");
wb.Document.GetElementById("F3").SetAttribute("Value", "Tester5123@hotmail.com");
wb.Document.GetElementById("F4").SetAttribute("Value", "Tester5123@hotmail.com");
wb.Document.GetElementById("F5").SetAttribute("Value", "limewire");
wb.Document.GetElementById("F6").SetAttribute("SelectedIndex", "1");
wb.Document.GetElementById("F7").SetAttribute("SelectedIndex", "2");
wb.Document.GetElementById("F8").SetAttribute("SelectedIndex", "5");
wb.Document.GetElementById("F9").SetAttribute("SelectedIndex", "20");
// updateText("Entered Data");
HtmlElementCollection elements = wb.Document.Body.All;
foreach (HtmlElement element in elements)
{
string valueAttribute = element.GetAttribute("value");
if (!string.IsNullOrEmpty(valueAttribute) && valueAttribute == "Sign Up")
{
element.InvokeMember("click");
//MessageBox.show("I am in"); //that messagebox shows normally.
break;
}
}
}
Please note that the Work() runs very correctly when it's called from the main thread. The problem lies in calling it from another thread.
Thanks in advance.