获取WebBrowser页面转向网址的两种办法

今天同学遇到一个问题,他制作的Html电子书光盘,在浏览页面的时候没有问题,但是在打开PDF、Word、Excel、PPT文件的时候,部分客户电脑可以打开,但是有些用户又打不开,经过检查是因为默认是通过浏览器去打开这些文件,但是不同用户的电脑浏览器安全设定可能不同,所以出现问题。

 

经过讨论,解决方案是制作一个浏览器程序,使用这个程序浏览页面,当页面进行跳转的时候监测即将转向的文件是否为需要外部程序开发的文件,如果是,则使用应用程序接管,并利用应用程序继承Windows的权限来打开文件。解决方案有了,主要的难点在于如何获取页面转向时的网址。

 

经过测试,写出了两个方法,一个是利用webBrowser1_Navigated方法,一个是利用webBrowser1_DocumentCompleted,具体代码如下,供大家参考。

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Text.RegularExpressions;

using System.Net;

namespace WindowsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate(Application.StartupPath + "\\index.htm");
        }

        private string strOpenFile = "";
        private string strFilePath = "";

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            string strUrl = e.Url.ToString();
            System.Text.RegularExpressions.MatchCollection mc = new Regex("file=(?<ListUrl>[\\s\\S][^&]+)&").Matches(strUrl);
            if (mc != null)
            {
                if (mc.Count > 0)
                {
                    strFilePath = mc[0].Groups["ListUrl"].Value;
                    MessageBox.Show(strFilePath);
                }
            }
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlDocument hd = webBrowser1.Document;
            hd.Encoding = Encoding.UTF8.WebName;
            HtmlElement he = hd.GetElementById("aa");
            if (he != null)
            {
                strOpenFile = he.GetAttribute("alt").ToString();
                he.AttachEventHandler("onclick", new EventHandler(link_Click));
            }
        }

        private void link_Click(object sender, EventArgs e)
        {
            System.Text.RegularExpressions.MatchCollection mc = new Regex("file=(?<ListUrl>[\\s\\S][^&]+)&").Matches(strOpenFile);
            if (mc != null)
            {
                if (mc.Count > 0)
                {
                    strFilePath = mc[0].Groups["ListUrl"].Value;
                    MessageBox.Show(strFilePath);
                }
            }
        }
    }
}

 

如需要相应代码,可以到我的微博(http://weibo.com/songhaipeng)给我留言。

posted on 2012-05-28 22:48  宋海鹏  阅读(2330)  评论(0编辑  收藏  举报

导航