Pergunta

I am quite new in visual C# and I'm trying to code an auto login program. Basically all i need is to know SetAttribute and InvokeMember for now.

To simplify the task, I have tried to make a form that will go to google, use SetAttribute to change query box to the user input and use InvokeMember to click "search" button. However code ignores the InvokeMember function when I try to run them in order.

Here is my code:

webBrowser1.Navigate("www.google.com");
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
webBrowser1.Document.GetElementById("q").SetAttribute("value", searchTXT.Text);
//MessageBox.Show(webBrowser1.Document.GetElementById("q").GetAttribute("value"));
webBrowser1.Document.GetElementById("btnK").InvokeMember("click");

it basically ignores the last line. However when I uncomment the messagebox, it works. It also works when I use a seperate button for clicking, so last line itself should be okay.

I think it is some kind of a delay problem. So I have to wait SetAttribute to finish its job before I call InvokeMember. I tried a while loop to put some delay but it didnt work. Is there any way to wait an operation to complete before proceeding? Is it the actual cause of my problem?

I would really appreciate any help, Thanks in Advance!

Foi útil?

Solução

Well eventually "System.Threading.Thread.Sleep(150);" did not work, and I noticed that for some reason

while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

terminates itself before the Web Browser completely loads. In order to make sure that the pages is loaded what I did was to create a bool variable called "wait". Then I changed the code to the following:

wait = true;
webBrowser1.Navigate("www.google.com");
while (wait==true) { Application.DoEvents(); }
webBrowser1.Document.GetElementById("q").SetAttribute("value", searchTXT.Text);
//MessageBox.Show(webBrowser1.Document.GetElementById("q").GetAttribute("value"));
webBrowser1.Document.GetElementById("btnK").InvokeMember("click");

and I double clicked webBrowser1 and set its "completed" event to be wait=false; which worked perfectly fine for me.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top