C#控制IE浏览器

项目-添加引用-COM,添加下面两个:

Microsoft Internet Controls
Microsoft HTML Object Library

private void button1_Click(object sender, EventArgs e)
{
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer();
ie.DocumentComplete += ie_DocumentComplete;
ie.Navigate("http://www.baidu.com");
ie.Visible = true;
compWait();
mshtml.HTMLDocument doc = ie.Document;
doc.getElementById("kw").innerText = "中国";
doc.getElementById("su").click();
}

private bool ie_read = false;
private void ie_DocumentComplete(object pDisp, ref object URL) //加载完成事件
{
ie_read = true;
}

private void compWait() //等待,直到加载完成
{
while (ie_read != true)
{
Application.DoEvents();
}
}
 

如果网页中没有设置id,只能通过name查找

mshtml.IHTMLElementCollection userids = doc.getElementsByName("userid");
foreach (mshtml.IHTMLElement userid in userids)
{
userid.innerText = "USERID";
}

控制已经打开的IE浏览器:

public static SHDocVw.InternetExplorer getInternetExploer(string url)
{
var shell = new Shell32.Shell();
var windows = (SHDocVw.IShellWindows)shell.Windows();
SHDocVw.InternetExplorer ie;
foreach (object window in windows)
{
ie = window as SHDocVw.InternetExplorer;
if (ie != null &&
string.Equals(System.IO.Path.GetFileName(ie.FullName),
"iexplore.exe", StringComparison.CurrentCultureIgnoreCase))
{
if (ie.LocationURL == url)
{
return ie;
}
}
}
return null;
}

Frame的控制

mshtml.HTMLDocument doc2 = ie.Document;
var frame = doc2.frames.item(0);
var doc = frame.Document;
doc.getElementById...
 

原文地址:https://www.cnblogs.com/soundcode/p/10918829.html