1. 程式人生 > >C#控制IE瀏覽器

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...