65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C# 打开 IE 并触发事件

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (6投票s)

2009年11月4日

CPOL

2分钟阅读

viewsIcon

123454

如何使用 C# 代码打开 Internet Explorer,并在加载的页面中触发事件。

引言

本文档展示了代码,用于在新 Internet Explorer 窗口中打开网站,并找到网站内的控件并在该网站中触发事件。

Using the Code

最近,我遇到一个需求,需要使用 C# 在 Internet Explorer 中打开网站并触发事件(例如,打开 GMail 并填写用户 ID 和密码,然后触发登录按钮事件)。这很有意思…… 我使用的代码如下所示

InternetExplorer gmailurl = new InternetExplorer();
object mVal = System.Reflection.Missing.Value;
gmailurl.Navigate("http://www.gmail.com", ref mVal, ref mVal, ref mVal, ref mVal);

HTMLDocument myDoc = new HTMLDocumentClass();
System.Threading.Thread.Sleep(500);
myDoc = (HTMLDocument)gmailurl.Document;
HTMLInputElement userID = (HTMLInputElement)myDoc.all.item("username", 0);
userID.value = "youruserid";
HTMLInputElement pwd = (HTMLInputElement)myDoc.all.item("pwd", 0);
pwd.value = "yourpassword";
HTMLInputElement btnsubmit = (HTMLInputElement)myDoc.all.item("signIn", 0);
btnsubmit.click();
gmailurl.Visible = true;

在上面的代码中,类 InternetExplorer 来自 SHDocVw.dll,您可以从以下网址下载: http://www.dll-files.com/dllindex/dll-files.shtml?shdocvw

我使用的另一个引用是 HTMLDocument 类,来自 MSHTML,您可以从 COM 引用中获取它(在解决方案资源管理器中右键单击项目,然后单击“添加引用”,转到“COM”选项卡,并添加 Microsoft HTML 对象库)。

在上面的代码中:

HTMLInputElement userID = (HTMLInputElement)myDoc.all.item("username", 0);

用于查找用户名文本框,其中“username”只是 GMail 网站中使用的输入文本框控件的名称。 您可以通过查看 GMail 网站的源代码来找到它;密码和登录按钮也是如此。

上面的代码将在服务器端打开 Internet Explorer,而不是在客户端打开,所以我选择了客户端脚本来完成上述工作。 这是我使用的 VBScript 代码

Function getgmail()
    Dim count
    Dim ie
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Navigate "http://www.gmail.com"
    Do While ie.Busy Or (ie.READYSTATE <> 4)
        count = count+1
    Loop
    ie.Visible=True
    ie.document.all.username.value = "youruserID"
    ie.document.all.pwd.value = "yourpassword"
    ie.document.all.signIn.click
END Function

关注点

我尝试了上述解决方案的许多方法;我尝试使用 ProcessStartInfoIHTMLDocument,然后是 HttpWebRequest 类,但这些方法都没有满足我的要求。 另一个我注意到的点是,在某些网站上,某些控件可能没有名称(例如,username、pwd、signIn ...)属性,所以我不得不努力寻找控件,并且我发现使用网站中每个控件的唯一 ID 有助于解决问题。

希望这能帮助到某人...... 祝您编码愉快! :-)

© . All rights reserved.