标签归档:WebBrowser

c#(.net)基于WebBrowser开发的简单的浏览器

用webbrowser控件做的浏览器,界面仿ie9,虽然很丑,懒得贴图,包含收藏夹功能(网上找的,研究中····),其他都是些webbrowser的方法,Internet选项用的是命令直接打开的方式,添加到收藏夹用的是创建快捷方式的方法实现的。

附上代码:

 

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 IWshRuntimeLibrary;
using Microsoft.Win32;
using System.IO;
namespace MyBrowser
{
    public partial class MainForm : Form
    {

        string url = "www.baidu.com";

        string favorfolder = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
        public MainForm()
        {
            InitializeComponent();
            this.webBrowser1.StatusTextChanged += new EventHandler(webBrowser1_StatusTextChanged);
            ListMenuItem(收藏夹ToolStripMenuItem, new DirectoryInfo(favorfolder));
            // Refresh();
        }

        public void ListMenuItem(ToolStripMenuItem toolstripmenuitem, FileSystemInfo info)             //生成收藏夹菜单的函数,递归使用
        {
            if (!info.Exists) return;
            DirectoryInfo dir = info as DirectoryInfo;
            //不是目录
            if (dir == null) return;

            FileSystemInfo[] files = dir.GetFileSystemInfos();
            ToolStripMenuItem[] ShouCangsMenuItem = new ToolStripMenuItem[files.Length];
            for (int i = 0; i < files.Length; i++)
            {

                FileInfo file = files[i] as FileInfo;
                ShouCangsMenuItem[i] = new System.Windows.Forms.ToolStripMenuItem();

                //是文件
                if (file != null)
                {
                    if (file.Extension == ".url")
                    {
                        //ShouCangsMenuItem[i].Image = global::MyBrowser.Properties.Resources.ie1;//菜单项图片
                        string str = file.Name;             //获取收藏夹的文件名(都是URL文件)
                        str = str.Remove(str.Length - 4);     //去掉.url后缀名

                        ShouCangsMenuItem[i].Text = str;          //然后赋值给菜单文本

                        StreamReader sr = file.OpenText();//获取文件输入流

                        List src = new List();

                        string source = null;
                        while ((source = sr.ReadLine()) != null)
                        {
                            src.Add(source);//文件所有行添加到List中
                        }

                        ShouCangsMenuItem[i].Tag = src;

                        foreach (string stri in src)
                        {
                            if (stri != null)
                            {
                                if (stri.StartsWith("URL="))
                                {
                                    ShouCangsMenuItem[i].ToolTipText = stri.Remove(0, 4);//ToolTipText
                                }
                            }
                        }

                        toolstripmenuitem.DropDownItems.Add(ShouCangsMenuItem[i]);   //生成的子菜单添加到上一级菜单
                        ShouCangsMenuItem[i].Click += new EventHandler(ShouCangsMenuItem_Click);          //为生成的子菜单添加单击消息(可写一个消息处理函数,这里就不例出来了)
                    }
                }
                //对于子目录,进行递归调用
                else
                {
                    DirectoryInfo Direct = files[i] as DirectoryInfo;
                    ShouCangsMenuItem[i].Text = files[i].Name;
                    //ShouCangsMenuItem[i].Image = global::MyBrowser.Properties.Resources.folder2;//菜单项图片
                    ShouCangsMenuItem[i].ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
                    ShouCangsMenuItem[i].ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.SizeToFit;
                    toolstripmenuitem.DropDownItems.Add(ShouCangsMenuItem[i]);       //生成的子菜单添加到上一级菜单
                    ListMenuItem(ShouCangsMenuItem[i], new DirectoryInfo(Direct.FullName));   //递归使用,生成子菜单
                }
            }
        }

        private void ShouCangsMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            string[] tar = ((List)item.Tag).ToArray();
            for (int i = 0; i < tar.Length; i++)
            {
                if (tar[i] != null)
                {
                    if (tar[i].StartsWith("URL="))
                    {
                        webBrowser1.Navigate(tar[i].Remove(0, 4));
                    }
                }
            }
        }

        /////////////////////////////底部信息/////////////////////////////////
        private void webBrowser1_StatusTextChanged(Object obj, EventArgs e)
        {
            this.label1.Text = webBrowser1.StatusText;
        }
        private void buttongo_Click(object sender, EventArgs e)
        {
            url = this.text_url.Text;
            this.webBrowser1.Navigate(url);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Random rd = new Random();
            this.BackColor = Color.FromArgb(rd.Next(255), rd.Next(255), rd.Next(255));//随机背景颜色

            this.webBrowser1.Width = base.Width - 10;
            this.webBrowser1.Height = base.Height - 80;
            webBrowser1.GoHome();

            Invalidate();
        }

        private void button_home_Click(object sender, EventArgs e)
        {
            this.webBrowser1.GoHome();
        }

        private void button_fresh_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Refresh();
        }

        private void button_back_Click(object sender, EventArgs e)
        {
            this.webBrowser1.GoBack();
        }

        private void button_forward_Click(object sender, EventArgs e)
        {
            this.webBrowser1.GoForward();
        }
        /////////////////////////////回车事件/////////////////////////////////
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                url = this.text_url.Text;
                this.webBrowser1.Navigate(url);
            }
        }

        private void text_url_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                url = this.text_url.Text;
                this.webBrowser1.Navigate(url);
            }
        }
        ////////////////////////////////////////////////////////////////////

        private void Form1_Resize(object sender, EventArgs e)
        {
            //this.webBrowser1.Width = base.Width-10;
            //this.webBrowser1.Height = base.Height - 95;
            this.panel1.Width = base.Width - 10;
            this.panel1.Height = base.Height - 90;
            this.toolStrip1.Location = new Point(base.Width - 60, this.toolStrip1.Location.Y);
            this.button_go.Location = new Point(base.Width - 193, this.button_go.Location.Y);
            this.text_url.Size = new Size(base.Width - 300, this.text_url.Size.Height);

        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser1.ShowSaveAsDialog();
        }

        private void 查找ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            webBrowser1.GoSearch();
        }

        private void 页面属性ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser1.ShowPropertiesDialog();
        }

        private void 打印ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            webBrowser1.ShowPrintDialog();
        }

        private void 打印预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser1.ShowPrintPreviewDialog();
        }

        private void 页面设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser1.ShowPageSetupDialog();
        }

        private void 关于MyToolStripMenuItem_Click(object sender, EventArgs e)
        {

            MessageBox.Show("My Browser made by DormyMo  \n www.7mdm.com \n \nQQ:440056060\n\n" + "ie版本" + webBrowser1.Version.ToString());
        }

        private void internet选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("inetcpl.cpl");

        }
        /////////////////////////////设置按钮效果/////////////////////////////////
        private void toolStripDropDownButton1_MouseEnter(object sender, EventArgs e)
        {
            this.toolStripDropDownButton1.Image = MyBrowser.Properties.Resources.shezhi2;
        }

        private void toolStripDropDownButton1_MouseLeave(object sender, EventArgs e)
        {
            this.toolStripDropDownButton1.Image = MyBrowser.Properties.Resources.shezhi;
        }
        //////////////////////////////////////////////////////////////////////////

        /////////////////////////////缩放/////////////////////////////////
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.Body.Style = "zoom:0.5";
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.Body.Style = "zoom:0.75";
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.Body.Style = "zoom:1.0";
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.Body.Style = "zoom:1.25";
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.Body.Style = "zoom:1.5";
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.Body.Style = "zoom:2.0";
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.Body.Style = "zoom:4.0";
        }
        //////////////////////////////////////////////////////////////

        /////////////////////////////显示网页标题/////////////////////////////////
        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            this.Text = this.webBrowser1.DocumentTitle + "                               made by DormyMo";
        }
        /////////////////////////////新窗口在原始窗口打开/////////////////////////////////
        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)//当发生新窗口打开事件时
        {
            WebBrowser webBrowser_temp = (WebBrowser)sender;
            string newUrl = webBrowser_temp.Document.ActiveElement.GetAttribute("href");//截取url
            webBrowser1.Url = new Uri(newUrl);//把url传给webbrowser1
            e.Cancel = true; //取消ie操作
        }

        /////////////////////////////收藏夹按钮效果/////////////////////////////////
        private void toolStripDropDownButton2_MouseEnter(object sender, EventArgs e)
        {
            this.toolStripDropDownButton2.Image = MyBrowser.Properties.Resources.star2;
        }

        private void toolStripDropDownButton2_MouseLeave(object sender, EventArgs e)
        {
            this.toolStripDropDownButton2.Image = MyBrowser.Properties.Resources.star;
        }
        //////////////////////////////////////////////////////////////////////////

        private void 添加到收藏夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IWshShell_Class shell = new IWshShell_Class();
            IWshURLShortcut shortcut = null;
            string filename = this.webBrowser1.DocumentTitle;
            shortcut = shell.CreateShortcut(Environment.GetFolderPath(System.Environment.SpecialFolder.Favorites) + "\\" + filename + ".url") as IWshURLShortcut;
            shortcut.TargetPath = webBrowser1.Url.AbsoluteUri;

            shortcut.Save();
        }

        private void 百度一下ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            this.webBrowser1.Navigate("www.baidu.com");
        }

        private void 打开收藏夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(favorfolder);
        }

        private void 设为主页ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string key = @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main";
            string valueName = "Start Page";
            string value = webBrowser1.Url.AbsoluteUri;
            DialogResult Confirm = MessageBox.Show("你确定要执行修改主页的操作吗!?", "通过注册表来修改Internet Explore的主页", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (Confirm == DialogResult.OK)
            {
                Registry.SetValue(key, valueName, value);
                MessageBox.Show("你的浏览器主页已被更改为:" + webBrowser1.Url.AbsoluteUri, "恭喜您", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
    }
}

【源文件】

[转]C# WebBrowser 收藏夹完全解决方案

做了很久,自己编写的浏览器的收藏夹终于解决了,已经成全实现了收藏夹的功能。下面是我的解决方案,帖出来交流交流。欢迎各位高手拍砖。

 

//获取收藏夹路径
        string favorfolder = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);        //获取系统收藏夹路径

        //构造器
        public Form1()
        {
            ListMenuItem(收藏夹ToolStripMenuItem, new DirectoryInfo(favorfolder));
        }


public void ListMenuItem(ToolStripMenuItem toolstripmenuitem, FileSystemInfo info)             //生成收藏夹菜单的函数,递归使用
        {           
            if (!info.Exists) return;
            DirectoryInfo dir = info as DirectoryInfo;
            //不是目录 
            if (dir == null) return;

            FileSystemInfo[] files = dir.GetFileSystemInfos();
            ToolStripMenuItem[] ShouCangsMenuItem = new ToolStripMenuItem[files.Length];
            for (int i = 0; i < files.Length; i++)
            {
                
                FileInfo file = files[i] as FileInfo;                                
                ShouCangsMenuItem[i] = new System.Windows.Forms.ToolStripMenuItem();
               
                //是文件 
                if (file !=null)
                {
                    if (file.Extension == ".url")
                    {
                        ShouCangsMenuItem[i].Image = global::MyWebBrowser2010.Properties.Resources.ie1;//菜单项图片
                        string str = file.Name;             //获取收藏夹的文件名(都是URL文件)
                        str = str.Remove(str.Length - 4);     //去掉.url后缀名

                        ShouCangsMenuItem[i].Text = str;          //然后赋值给菜单文本

                        StreamReader sr = file.OpenText();//获取文件输入流


                        List src = new List();

                        string source = null;
                        while ((source = sr.ReadLine()) != null)
                        {
                            src.Add(source);//文件所有行添加到List中
                        }

                        ShouCangsMenuItem[i].Tag = src;

                        foreach (string stri in src)
                        {
                            if (stri != null)
                            {
                                if (stri.StartsWith("URL="))
                                {
                                    ShouCangsMenuItem[i].ToolTipText = stri.Remove(0,4);//ToolTipText
                                }
                            }
                        }

                        toolstripmenuitem.DropDownItems.Add(ShouCangsMenuItem[i]);   //生成的子菜单添加到上一级菜单
                        ShouCangsMenuItem[i].Click += new EventHandler(ShouCangsMenuItem_Click);          //为生成的子菜单添加单击消息(可写一个消息处理函数,这里就不例出来了)
                    }
                }                
                //对于子目录,进行递归调用 
                else
                {
                    DirectoryInfo Direct = files[i] as DirectoryInfo;                    
                    ShouCangsMenuItem[i].Text = files[i].Name;
                    ShouCangsMenuItem[i].Image = global::MyWebBrowser2010.Properties.Resources.folder2;//菜单项图片
                    ShouCangsMenuItem[i].ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
                    ShouCangsMenuItem[i].ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.SizeToFit;
                    toolstripmenuitem.DropDownItems.Add(ShouCangsMenuItem[i]);       //生成的子菜单添加到上一级菜单
                    ListMenuItem(ShouCangsMenuItem[i], new DirectoryInfo(Direct.FullName));   //递归使用,生成子菜单
                }
            }
        }

        private void ShouCangsMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            string[] tar=((List)item.Tag).ToArray();
            for (int i = 0; i < tar.Length; i++)
            {
                if (tar[i] != null)
                {
                    if (tar[i].StartsWith("URL="))
                    {
                        getCurrentBrowser().Navigate(tar[i].Remove(0, 4));
                    }
                }
            }
        }

c#为webbrowser添加一个添加到收藏夹功能(快捷方式的制作)

webbrowser没有这功能,只能自己写。

要创建快捷方式需要用到IWshRuntimeLibrary命名空间,在这里我们要USING一下。并在引用里添加一个COM,windows script host object model。

 

private void CreateShortCut()
        {
            string mysite = "http://" + iis + "/path/defaut.aspx";

            //创建Windows Script Host Shell类   
            IWshRuntimeLibrary.IWshShell_Class shell = new IWshRuntimeLibrary.IWshShell_ClassClass();

            if (this.Context.Parameters["ckFavorites"] == "1")
            {
                string fav = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Favorites) + "\\××××××××.url";
                //定义快捷方式文件   
                IWshRuntimeLibrary.IWshURLShortcut shortcut = shell.CreateShortcut(fav) as IWshRuntimeLibrary.IWshURLShortcut;
                shortcut.TargetPath = mysite;
                //保存快捷方式 
                shortcut.Save();
            }
            if (this.Context.Parameters["ckDesktop"] == "1")
            {
                string dsk = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\××××××××.url";
                IWshRuntimeLibrary.IWshURLShortcut shortcut = shell.CreateShortcut(dsk) as IWshRuntimeLibrary.IWshURLShortcut;
                shortcut.TargetPath = mysite;
                shortcut.Save();
            }
        }

c#WebBrowser自动滚屏方法

/// 
        /// 自动滚屏方法
        /// 
        /// 
        private void startScroll(string url)
        {
            webBrowser1.Navigate(string.Format(@"javascript:(function() {{var body = document.documentElement && document.compatMode == 'CSS1Compat' ?document.documentElement : document.body;clearInterval(window.timerAutoScroll);window.timerAutoScroll = setInterval(function() {{scrollBy(0, {0});if (body.scrollHeight <= body.clientHeight + body.scrollTop) {{clearInterval(window.timerAutoScroll);}}}}, {1});}})();", 800, 1));
        }

JS代码就能解决;

C# webBrowser禁止在新窗口打开,强制在本窗口打开

进行webBrower开发的时候,肯定都会遇到一个问题。
那就是怎么样强制在本窗口打开新窗口的问题。
网上最常见的解决方法就是,
在NewWindow事件中取得要打开的网址,取消打开新窗口,然后在本窗口打开要转向的网址
private void webBrowser_1_NewWindow(object sender, CancelEventArgs e)
{
WebBrowser webBrowser_temp = (WebBrowser)sender;
string newUrl = webBrowser_temp.Document.ActiveElement.GetAttribute(“href”);
webBrowser_1.Url = new Uri(newUrl);
e.Cancel = true;
}

虽然这种方法能够解决大部分的要求,但是治标不治本。
而且当网址里面还有汉字的时候就更加麻烦了,比如在百度MP3,歌曲名字都是汉字,和百度空间里面,大部分用户名都是汉字,所以取的网址都用乱码。虽然,可以对网址进行编码,但是并不是所有网页都是uft-8编码,对于如何得知网页的编码又是一个课题了。

最根本的方法就是重写了。
新建一个类

using System;
using System.Collections.Generic;
using System.Text;

namespace webTestRecorder
{

    public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser
    {
        System.Windows.Forms.AxHost.ConnectionPointCookie cookie;
        WebBrowserExtendedEvents events;

        //This method will be called to give you a chance to create your own event sink
        protected override void CreateSink()
        {
            //MAKE SURE TO CALL THE BASE or the normal events won't fire
            base.CreateSink();
            events = new WebBrowserExtendedEvents(this);
            cookie = new System.Windows.Forms.AxHost.ConnectionPointCookie(this.ActiveXInstance, events, typeof(DWebBrowserEvents2));
        }

        protected override void DetachSink()
        {
            if (null != cookie)
            {
                cookie.Disconnect();
                cookie = null;
            }
            base.DetachSink();
        }

        //This new event will fire when the page is navigating
        public event EventHandler BeforeNavigate;
        public event EventHandler BeforeNewWindow;

        protected void OnBeforeNewWindow(string url, out bool cancel)
        {
            EventHandler h = BeforeNewWindow;
            WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs(url, null);
            if (null != h)
            {
                h(this, args);
            }
            cancel = args.Cancel;
        }

        protected void OnBeforeNavigate(string url, string frame, out bool cancel)
        {
            EventHandler h = BeforeNavigate;
            WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs(url, frame);
            if (null != h)
            {
                h(this, args);
            }
            //Pass the cancellation chosen back out to the events
            cancel = args.Cancel;
        }
        //This class will capture events from the WebBrowser
        class WebBrowserExtendedEvents : System.Runtime.InteropServices.StandardOleMarshalObject, DWebBrowserEvents2
        {
            ExtendedWebBrowser _Browser;
            public WebBrowserExtendedEvents(ExtendedWebBrowser browser) { _Browser = browser; }

            //Implement whichever events you wish
            public void BeforeNavigate2(object pDisp, ref object URL, ref object flags, ref object targetFrameName, ref object postData, ref object headers, ref bool cancel)
            {
                _Browser.OnBeforeNavigate((string)URL, (string)targetFrameName, out cancel);
            }

            public void NewWindow3(object pDisp, ref bool cancel, ref object flags, ref object URLContext, ref object URL)
            {
                _Browser.OnBeforeNewWindow((string)URL, out cancel);
            }

        }
        [System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),
        System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch),
        System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
        public interface DWebBrowserEvents2
        {

            [System.Runtime.InteropServices.DispId(250)]
            void BeforeNavigate2(
                [System.Runtime.InteropServices.In,
                System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IDispatch)] object pDisp,
                [System.Runtime.InteropServices.In] ref object URL,
                [System.Runtime.InteropServices.In] ref object flags,
                [System.Runtime.InteropServices.In] ref object targetFrameName, [System.Runtime.InteropServices.In] ref object postData,
                [System.Runtime.InteropServices.In] ref object headers,
                [System.Runtime.InteropServices.In,
                System.Runtime.InteropServices.Out] ref bool cancel);
            [System.Runtime.InteropServices.DispId(273)]
            void NewWindow3(
                [System.Runtime.InteropServices.In,
                System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IDispatch)] object pDisp,
                [System.Runtime.InteropServices.In, System.Runtime.InteropServices.Out] ref bool cancel,
                [System.Runtime.InteropServices.In] ref object flags,
                [System.Runtime.InteropServices.In] ref object URLContext,
                [System.Runtime.InteropServices.In] ref object URL);

        }
    }

    public class WebBrowserExtendedNavigatingEventArgs : System.ComponentModel.CancelEventArgs
    {
        private string _Url;
        public string Url
        {
            get { return _Url; }
        }

        private string _Frame;
        public string Frame
        {
            get { return _Frame; }
        }

        public WebBrowserExtendedNavigatingEventArgs(string url, string frame)
            : base()
        {
            _Url = url;
            _Frame = frame;
        }
    }
}

 

然后把webBrowser换成我们重写的ExtendedWebBrowser,添加事件处理
ieBrowser = new ExtendedWebBrowser();
ieBrowser.BeforeNewWindow += new EventHandler(ieBrowser_BeforeNewWindow);

然后在其BeforeNewWindow事件中:

void ieBrowser_BeforeNewWindow(object sender, WebBrowserExtendedNavigatingEventArgs e) {
e.Cancel=true;
((ExtendedWebBrowser)sender).Navigate(e.Url);
}