从 C# 控制 IE?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/992436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Controlling IE from C#?
提问by ryeguy
How can I control IE form C#? I know that via COM you can do all sorts of interesting stuff, but looking at the SHDocVwnamespace 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?
如何控制 IE 表单 C#?我知道通过 COM 你可以做各种有趣的事情,但是一旦我将引用导入到我的项目中,看看SHDocVw命名空间,似乎没有那么多方法。例如,我将如何强制单击按钮?或者设置或读取页面上特定控件的值?一般来说,我如何通过 .NET 单独控制 IE 中的对象?
采纳答案by Ville Krumlinde
Here are some samples from code I've written to control IE, maybe it can help:
以下是我为控制 IE 而编写的一些代码示例,也许它可以提供帮助:
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;
}