zoukankan      html  css  js  c++  java
  • WPF中,在WebBrowser中操作源代码

    由于WPF的webBrowser控件与WINFORM的webBrowser控件非常的不一样,所以被折腾了一晚上,四处查阅相关资料,现将一些关键代码汇总一下。

    首先要引入Microsoft.mshtml.dll 地址是C:\Program Files\Microsoft.NET\Primary Interop Assemblies

    1、根据元素ID获取元素的值。

    比如要获取<img class="" id="regimg" src="/register/checkregcode.html?1287068791" width="80" height="22">这个标签里的src属性的值:

    mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)webBrowser1.Document;
    mshtml.IHTMLElement img = (mshtml.IHTMLElement)doc2.all.item("regimg", 0);

    string imgUrl = (string)img.getAttribute("src");

    2、填写表单,并确定

    mshtml.IHTMLElement loginname = (mshtml.IHTMLElement)doc2.all.item("loginname", 0);
    mshtml.IHTMLElement loginPW = (mshtml.IHTMLElement)doc2.all.item("password", 0);
    mshtml.IHTMLElement loginBT = (mshtml.IHTMLElement)doc2.all.item("formsubmit", 0);
    mshtml.IHTMLElement loginYZ = (mshtml.IHTMLElement)doc2.all.item("regcode", 0);
    loginname.setAttribute("value", tbLoginName.Text);
    loginPW.setAttribute("value", tbLoginPassWord.Password);
    loginYZ.setAttribute("value", tbYZ.Text);
    loginBT.click();

    3、获取源码

    textBox1.Text = doc2.body.innerHTML;

    4、执行JS

    mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)doc2.parentWindow;
    win.execScript("changeRegImg()", "javascript");//使用JS

    5、禁止JS,WPF下目前发现唯一适用的一种方法:

    public void HideScriptErrors(WebBrowser wb, bool Hide)
    {

    FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);

    if (fiComWebBrowser == null) return;

    object objComWebBrowser = fiComWebBrowser.GetValue(wb);

    if (objComWebBrowser == null) return;

    objComWebBrowser.GetType().InvokeMember(

    "Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });

    }

    void webBrowser1_Navigated(object sender, NavigationEventArgs e)
    {

    HideScriptErrors(webBrowser1,

    true);

    }

    作者:王春明 出处:http://wangchunming.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    软件构造—— 实验二 lex词法分析
    软件构造-实验1 根据状态转换图手工构造词法扫描器
    PHP——实验四 PHP操作数据库
    判断是不是素数
    hexo和github pages的关系
    Python的map,reduce,filter函数
    CentOS源码更新Linux最新内核
    CentOS打Meltdown等漏洞的补丁包
    let申明与const申明
    正则表达式
  • 原文地址:https://www.cnblogs.com/wangchunming/p/2673259.html
Copyright © 2011-2022 走看看