2014年12月23日
C#控制IE浏览器自动执行百度搜索
C#入门级选手尝试实现的功能,界面简单粗暴,请勿见笑,还请各路高手多多指点。
单击下图中的“autoSearchInBaidu”按钮,C#应用程序将自行开启一个新的IE进程,并输入”C#入门”,实现搜索。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using mshtml;//需在引用中添加 using SHDocVw;//需在引用中添加,即 Microsoft Internet controls. using System.Runtime.InteropServices; using System.Threading;//手动添加该命名空间 namespace autoSearchBaidu { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SHDocVw.InternetExplorer ieWnd = new SHDocVw.InternetExplorer(); object missing = null; mshtml.IHTMLDocument2 ieDoc; ieWnd.Visible = true; ieWnd.Navigate("http://www.baidu.com", ref missing, ref missing, ref missing, ref missing); while (ieWnd.Busy || ieWnd.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE) { Thread.Sleep(500); } ieDoc = (mshtml.IHTMLDocument2)ieWnd.Document; mshtml.HTMLInputElementClass input; //设定要搜索的内容,百度搜索页面检测到输入内容后会自动搜索,不需要点击搜索按钮 //如果要实现搜索按钮,实现原理与此处一致 foreach (mshtml.IHTMLElement ieElement in ieDoc.all) { if (ieElement.tagName.ToUpper().Equals("INPUT")) { input = ((mshtml.HTMLInputElementClass)ieElement); if (input.name == "wd") { input.value = "C#入门"; break; } } } } } } |
实现这个功能时,遇到了两个比较难解决的问题,记录下来供需要的同学参考:
SHDocVw开启新IE进程时报错80070002的临时解决方案
“对 COM 组件的调用返回了错误 HRESULT E_FAIL”解决方案