Reputation: 15071
I'm trying to automate logging into a particular site. It seems like a typical form with two text inputs (username, password) and a button of type 'submit'. All three have ids so I can easily call GetElementById for each.
My Code looks similar to this:
webBrowser1.Document.GetElementById("username").SetAttribute("Value", "myUser");
webBrowser1.Document.GetElementById("password").SetAttribute("Value", "myPass");
webBrowser1.Document.GetElementById("submitButton").InvokeMember("Click");
This (sorta) works. The values get set, and the form does submit/request is sent to the server. But I immediately get a javascript error. If I remove the 'Click' line and let my program load the page/populate the username/password and I manually click on the button - everything works 100%.
Okay I thought....I don't need to click. I can just use the Keyboard! Three tabs followed by enter successfully logs me in. So I tried to use SendKeys.Send()
Thread.Sleep(250);
SendKeys.Send("{TAB}");
Thread.Sleep(250);
SendKeys.Send("{TAB}");
Thread.Sleep(250);
SendKeys.Send("{TAB}");
Thread.Sleep(250);
SendKeys.Send("{ENTER}");
Originally it was one line, I introduced the delays while debugging but to no avail. The code above produces the exact same result as when I do the automated click - a javascript error and the following page does not load.
But if I press tab,tab,tab,enter - it does work.
I went one step further, if keep the SendKeys.Send("{TAB}") code, my automation program will fill the username/password and successfully navigate focus to the submit button. If I press enter on the keyboard, no javascript error and everything is great. But if I use SendKeys.Send("{ENTER}") - nothing works.
I was under the impression that SendKeys.Send generated a 'real' keypress as far as the Windows OS is concerned?
Can anyone tell me what is going on and how I can get this login to work with the WebBrowser control?
Upvotes: 0
Views: 634
Reputation: 61666
Hard to guess, but try it like this:
async Task SendSomeKeys()
{
await Task.Delay(250);
SendKeys.Send("{TAB}");
await Task.Delay(250);
SendKeys.Send("{TAB}");
await Task.Delay(250);
SendKeys.Send("{TAB}");
await Task.Delay(250);
SendKeys.Send("{ENTER}");
}
The difference is, you'd send keys asynchronously this way, giving the browser a chance to process Windows messages between keystrokes (unlike with Thread.Sleep
). So, it'd be more close to manual actions. If that works, the same approach may work for SetAttribute
/InvokeMember
.
Upvotes: 1