How can I control IE form C#? I know that via COM you can do all sorts of interesting stuff, but looking at the SHDocVw namespace once I import the reference into my project there doesn't seem to be that many methods. For example, how would I force a button to be clicked? Or set or read the value of a specific control on a page? In general, how can I individually control an object in IE though .NET?
A:
This maybe a good place to start. I know it's aimed at unit testing, but it automates control over IE and firefox and it's open source so you can download the code to see how they do it.
Hope it helps
WestDiscGolf
2009-06-14 09:19:24
+2
A:
Here are some samples from code I've written to control IE, maybe it can help:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
//...
void SetField(WebBrowser wb, string formname, string fieldname, string fieldvalue) {
HtmlElement f = wb.Document.Forms[formname].All[fieldname];
f.SetAttribute("value", fieldvalue);
}
void SetRadio(WebBrowser wb, string formname, string fieldname, bool isChecked) {
HtmlElement f = wb.Document.Forms[formname].All[fieldname];
f.SetAttribute("checked", isChecked ? "True" : "False");
}
void SubmitForm(WebBrowser wb, string formname) {
HtmlElement f = wb.Document.Forms[formname];
f.InvokeMember("submit");
}
void ClickButtonAndWait(WebBrowser wb, string buttonname,int timeOut) {
HtmlElement f = wb.Document.All[buttonname];
webReady = false;
f.InvokeMember("click");
DateTime endTime = DateTime.Now.AddSeconds(timeOut);
bool finished = false;
while (!finished) {
if (webReady)
finished = true;
Application.DoEvents();
if (aborted)
throw new EUserAborted();
Thread.Sleep(50);
if ((timeOut != 0) && (DateTime.Now>endTime)) {
finished = true;
}
}
}
void ClickButtonAndWait(WebBrowser wb, string buttonname) {
ClickButtonAndWait(wb, buttonname, 0);
}
void Navigate(string url,int timeOut) {
webReady = false;
webBrowser1.Navigate(url);
DateTime endTime = DateTime.Now.AddSeconds(timeOut);
bool finished = false;
while (!finished) {
if (webReady)
finished = true;
Application.DoEvents();
if (aborted)
throw new EUserAborted();
Thread.Sleep(50);
if ((timeOut != 0) && (DateTime.Now > endTime)) {
finished = true;
}
}
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
webReady = true;
}
Ville Krumlinde
2009-06-14 09:29:33
Thanks, the webbrowser class was what I was looking for.
ryeguy
2009-06-15 02:14:30