WPF使用Webbrowser操作网页的主要代码

复制代码
1,引用mshtml.dll

using mshtml;
2,获取元素属性值

IHTMLDocument2 doc2=(IHTMLDocument)webbrowser1.Document;
IHTMLElement img=(IHTMLElement)doc2.all.item("regimg",0);
string imgUrl=(string)img.getAttribute("src");
3,取表单控件


IHTMLElement loginName=(IHTMLElement)doc2.all.item("loginname",0);
IHTMLElement loginPW=(IHTMLElement)doc2.all.item("password",0);
IHTMLElement loingYZM=(IHTMLElement)doc2.all.item("regcode",0);
IHTMLElement loginBT=(IHTMLElement)doc2.all.item("formsubmit",0);
4,填写表单控件

loginName.setAttribute("value",tbLoginName.Text);
loginPW.setAttribute("value",tbLoginPassWord.Password);
loginYZM.setAttribute("value",tbYZ.Text);
5,点击按钮

loginBT.click();
6,执行js脚本

方法1:

IHTMLwindow win=(IHTMLWindow2)doc2.parentWindows;
win.execScript("alert('hello!')","javascript");
方法2:

webbrowser1.InvokeScript("eval","alert('hello!')");
7,屏蔽alert、confirm等,通过重定义实现

private voie webbrowser1_navigated(object sender,WebBroserNavigatedEventArgs e)
{
    IHTMLWindow2 win=(IHTMLWindow2)webbrowser1.Document.Window.DomWindow;
    string s=@"window.alert=null; window.onerror=null;window.confirm=null; windows.open=null; window.showModalDialg=null;";
    win.execScript(s,"javascript");
}
8,接收js消息

复制代码
[ComVisible(true)]  //这句要加到类定义前,可与COM通信

private void webbrowser1_Navigated(objec sender,WebBrowserNavigatedEventargs e)
{
    IHTMLWindow2 win=(IHTMLWindow2)webbrowser1.Document.Window.DomWindow;
    //假设把alert消息传出来处理
    string s=@"function alert(str){window.external.procMessage(str);}";
    win.execScript(s,"javascript");
    webbrowser1.ObjectForScripting=this;  //指定脚本消息送到当前实例处理
}

//处理脚本消息的方法
public void procMessage(string s)
{
    MessageBox.Show("脚本消息:"+s);
}
复制代码

 

posted @   大da脸  阅读(934)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示