C# winform自动点击webbrowser网页confirm/alert确定按钮

  winform编程中使用webBrowser浏览网页或者采集数据时,当网页某些调用confirm或者alert弹出对话框(确定/取消)时,会导致javascript代码的执行被挂起,没有人工操作时就无法执行下一步的操作,如果是采集数据就很麻烦,无法实现自动化。因此怎样实现让程序自动点击确定或者取消按钮成为关键。

  实现winform自动点击webbrowser网页confirm/alert的确定按钮,原理就是用execScript重写confirm,alert等系统函数return true【confirm】或者空函数体【alert】,这样就不会挂起js代码,继续下面的javascript代码执行。

  源代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//下面2个组件需要在vs中添加引用
using mshtml;//添加引用 -> .Net ->Microsoft.mshtml
using SHDocVw;//添加引用 ->com->MicroSoft Internet Controls 
namespace AutoClickConfirm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SHDocVw.WebBrowser wb;
        mshtml.IHTMLDocument2 doc;
        private void btnNavigator_Click(object sender, EventArgs e)
        {
            string url = txtURL.Text.Trim().ToLower();
            if (url.StartsWith("http://") || url.StartsWith("https://"))
            {
                webBrowser1.Navigate(url);
                wb = webBrowser1.ActiveXInstance as SHDocVw.WebBrowser;
                wb.NavigateComplete2 += new DWebBrowserEvents2_NavigateComplete2EventHandler(wb_NavigateComplete2);
               
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        void wb_NavigateComplete2(object pDisp, ref object URL)
        {
            doc = wb.Document as mshtml.IHTMLDocument2;
//执行javascript脚本,覆盖系统的confirm函数,直接return true,这样调用confirm函数都会执行到确认按钮了,同理可以重写系统中的其他函数
            doc.parentWindow.execScript("function confirm(){return true;}", "javascript");
            doc.parentWindow.execScript("function alert(){}", "javascript");//设置为alert为空函数体,就不会挂起javascript代码执行了
        }
    }
}

源代码下载:C# winform自动点击confirm确定按钮源代码

加支付宝好友偷能量挖...


原创文章,转载请注明出处:C# winform自动点击webbrowser网页confirm/alert确定按钮

评论(0)Web开发网
阅读(1732)喜欢(0)Asp.Net/C#/WCF