C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# Miniblink浏览器

C#基于Miniblink控件编写一个简易的浏览器

作者:搬砖的诗人Z

miniblink是一款精简小巧的浏览器控件,基于chromium精简而成,是市面上最小巧的chromium内核控件没有之一,本文将结合C#和Miniblink编写一个简易的浏览器,感兴趣的可以了解下

效果图

项目结构

实现代码

using Miniblink;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;
using XinShiYun_PlatformTools.Common;

namespace XinShiYun_PlatformTools
{
    public partial class Chrome : Form
    {
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

        /// <summary>
        /// 默认浏览器
        /// </summary>
        MiniblinkBrowser blinkBrowser;

        MouseHook mouse = new MouseHook();

        JsonHelper jsonHelper = new JsonHelper();

        public List<FavoriteModel> favoriteModels = new List<FavoriteModel>();

        WebBrowser webBrowser = new WebBrowser();

        string pageUrl = "";

        public Chrome(string[] args)
        {
            InitializeComponent();

            webBrowser.Visible = false;
            this.Controls.Add(webBrowser);


            if (args.Count() > 0)
            {
                pageUrl = args[0];
                if (pageUrl.Contains("proplat:"))
                {
                    pageUrl = pageUrl.Substring(14, pageUrl.Length - 14);
                }
            }

            this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;

            // Win32.SetClassLong(this.Handle, Win32.GCL_STYLE, Win32.GetClassLong(this.Handle, Win32.GCL_STYLE) | Win32.CS_DropSHADOW);

            myTab.Height = 50;
            SetStyles();

            //mouse.OnMouseActivity += new MouseEventHandler(mouse_OnMouseActivity);
            //mouse.Start();

            formStyleControl.ClickMaxEvent += FormStyleControl_ClickMaxEvent;
            formStyleControl.ClickMinEvent += FormStyleControl_ClickMinEvent;
            taskRegion.EnterSearchEvent += TaskRegion_EnterSearchEvent;
            taskRegion.ClickCollectionEvent += TaskRegion_ClickCollectionEvent;
            taskRegion.ClickFilesEvent += TaskRegion_ClickFilesEvent;
            taskRegion.ClickRefreshEvent += TaskRegion_ClickRefreshEvent;
            taskRegion.ClickLeftEvent += TaskRegion_ClickLeftEvent;
            taskRegion.ClickRightEvent += TaskRegion_ClickRightEvent;

            myTab.AddEvent += MyTab_AddEvent;
            myTab.ClickTabEvent += MyTab_ClickTabEvent;
            myTab.ClickCloseTabEvent += MyTab_ClickCloseTabEvent;

            blinkBrowser = new MiniblinkBrowser();
            blinkBrowser.Name = "blinkBrowser_1";
            blinkBrowser.Dock = DockStyle.Fill;
            blinkBrowser.NavigateBefore += BlinkBrowser_NavigateBefore;
            blinkBrowser.DocumentReady += BlinkBrowser_DocumentReady;
            blinkBrowser.Download += BlinkBrowser_Download;

            myTab.ActiveTab.myBlinkBrowser = blinkBrowser;
            panel_Page.Controls.Add(blinkBrowser);

            LoadFav();

            if (!String.IsNullOrEmpty(pageUrl))
            {
                taskRegion.SearchText = pageUrl;
                LoadChromeUrl(blinkBrowser, pageUrl);
            }

        }

        private void BlinkBrowser_Download(object sender, DownloadEventArgs e)
        {
            try
            {
                var cookie = blinkBrowser.Cookies.GetJSESSIONID();

                if (cookie != null)
                {
                    // MainView mainView = new MainView(e.Url, cookie.Value);
                     mainView.WindowState = FormWindowState.Maximized;
                    // mainView.ShowDialog();

                    InternetSetCookie(e.Url, "JSESSIONID", cookie.Value);
                    webBrowser.Url = new Uri(e.Url);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
           
        }

        private void FormStyleControl_ClickMinEvent(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        /// <summary>
        /// 注册注册表
        /// </summary>
        private void Register()
        {
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "Config\\Register.txt";
            if (File.Exists(filePath))
            {
                string value = TxtHelper.ReadText(filePath).Trim();
                if (value == "0")
                {
                    //未注册
                    RegisterTableHelper.Reg("proplat");
                    TxtHelper.WriteText(filePath, "1");
                }
            }
            else
            {
                RegisterTableHelper.Reg("proplat");
                TxtHelper.WriteText(filePath, "1");
            }

        }

        /// <summary>
        /// 前进
        /// </summary>
        private void TaskRegion_ClickRightEvent(object sender, EventArgs e)
        {
            var tab = myTab.ActiveTab;
            if (tab == null)
                return;

            if (tab.myBlinkBrowser == null)
                return;

            tab.myBlinkBrowser.GoForward();

            taskRegion.IsBackPage = tab.myBlinkBrowser.CanGoBack;
            taskRegion.IsForwardPage = tab.myBlinkBrowser.CanGoForward;
            taskRegion.Refresh();
        }

        /// <summary>
        /// 后退
        /// </summary>
        private void TaskRegion_ClickLeftEvent(object sender, EventArgs e)
        {
            var tab = myTab.ActiveTab;
            if (tab == null)
                return;

            if (tab.myBlinkBrowser == null)
                return;

            tab.myBlinkBrowser.GoBack();

            taskRegion.IsBackPage = tab.myBlinkBrowser.CanGoBack;
            taskRegion.IsForwardPage = tab.myBlinkBrowser.CanGoForward;
            taskRegion.Refresh();
        }

        private void TaskRegion_ClickRefreshEvent(object sender, EventArgs e)
        {
            var tab = myTab.ActiveTab;
            if (tab == null)
                return;

            tab.myBlinkBrowser.Reload();
        }

        private void LoadFav()
        {
            var list = jsonHelper.ReadFavorite();
            favoriteModels = list;

            if (favoriteModels == null)
                return;
            if (favoriteModels.Count() <= 0)
                return;
            foreach (var item in favoriteModels)
            {
                contextMenuStrip_Fav.Items.Add(item.Title);
            }
        }

        private void TaskRegion_ClickFilesEvent(object sender, EventArgs e)
        {
            contextMenuStrip_Fav.Show(Control.MousePosition);
        }

        private void TaskRegion_ClickCollectionEvent(object sender, EventArgs e)
        {
            var tab = myTab.ActiveTab;
            if (tab == null)
                return;
            if (String.IsNullOrEmpty(tab.urlLink.Trim()))
                return;

            FavoriteModel model = new FavoriteModel();
            model.Title = tab.TabTitle;
            model.Url = tab.urlLink;
            jsonHelper.AddFavorite(model);
            LoadFav();

            MessageBox.Show("收藏成功");
        }

        /// <summary>
        /// 关闭标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="tabPage"></param>
        private void MyTab_ClickCloseTabEvent(object sender, EventArgs e, MiniblinkBrowser browser)
        {
            if (browser != null)
            {
                panel_Page.Controls.Remove(browser);
                taskRegion.SearchText = "";
            }
        }


        private void MyTab_ClickTabEvent(object sender, EventArgs e, TabPage tabPage)
        {
            foreach (Control item in panel_Page.Controls)
            {
                if (item.Name.Contains("blinkBrowser_"))
                {
                    item.Visible = false;
                }
            }
            taskRegion.SearchText = "";
            string name = "blinkBrowser_" + tabPage.Tag.ToString();
            var list = panel_Page.Controls.Find(name, false);
            if (list == null)
                return;

            if (list.Count() <= 0)
                return;

            var mytab = (MiniblinkBrowser)list.First() as MiniblinkBrowser;
            mytab.Visible = true;
            taskRegion.SearchText = myTab.ActiveTab.urlLink;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="tabPage"></param>
        private void MyTab_AddEvent(object sender, EventArgs e, TabPage tabPage)
        {
            foreach (Control item in panel_Page.Controls)
            {
                if (item.Name.Contains("blinkBrowser_"))
                {
                    item.Visible = false;
                }
            }
            taskRegion.SearchText = "";

            MiniblinkBrowser mblinkBrowser = new MiniblinkBrowser();
            mblinkBrowser.Name = "blinkBrowser_" + tabPage.Tag.ToString();
            mblinkBrowser.Dock = DockStyle.Fill;
            mblinkBrowser.NavigateBefore += BlinkBrowser_NavigateBefore;
            mblinkBrowser.DocumentReady += BlinkBrowser_DocumentReady;
            tabPage.myBlinkBrowser = mblinkBrowser;
            panel_Page.Controls.Add(mblinkBrowser);

        }

        private void BlinkBrowser_NavigateBefore(object sender, Miniblink.NavigateEventArgs e)
        {
            if (e.Type == NavigateType.BlankLink)
            {
                try
                {
                    if (e.Url.Contains("downLoadYjsdHZJzdy"))
                    {
                        blinkBrowser.Cookies.GetCookies(e.Url);
                        var cookie = blinkBrowser.Cookies.GetJSESSIONID();

                        if (cookie != null)
                        {
                            InternetSetCookie(e.Url, "JSESSIONID", cookie.Value);
                            webBrowser.Url = new Uri(e.Url);
                        }
                    }
                    else
                    {
                        myTab.AddTabFunction();
                        MyTab_Add(e.Url);
                    }
                }
                catch (Exception ex)
                {
                 
                }
             
            }
        }

        private void MyTab_Add(string url)
        {
            if (myTab.ActiveTab == null)
                return;

            foreach (Control item in panel_Page.Controls)
            {
                if (item.Name.Contains("blinkBrowser_"))
                {
                    item.Visible = false;
                }
            }

            TabPage tabPage = myTab.ActiveTab;
            MiniblinkBrowser blinkBrowser = new MiniblinkBrowser();
            blinkBrowser.Name = "blinkBrowser_" + tabPage.Tag.ToString();
            blinkBrowser.Dock = DockStyle.Fill;
            blinkBrowser.NavigateBefore += BlinkBrowser_NavigateBefore;
            blinkBrowser.DocumentReady += BlinkBrowser_DocumentReady;

            tabPage.myBlinkBrowser = blinkBrowser;
            tabPage.urlLink = url;
            panel_Page.Controls.Add(blinkBrowser);

            LoadChromeUrl(blinkBrowser, url);
        }

        private void BlinkBrowser_DocumentReady(object sender, DocumentReadyEventArgs e)
        {
            try
            {
                taskRegion.SearchText = e.Frame.Url;

                TabPage tabPage = myTab.ActiveTab;
                if (tabPage != null)
                {
                    tabPage.urlLink = e.Frame.Url;
                }

                if (myTab.ActiveTab != null)
                {
                    myTab.ActiveTab.TabTitle = myTab.ActiveTab.myBlinkBrowser.DocumentTitle;
                }
                ShowForwardAndBack();
                myTab.ActiveTab.myBlinkBrowser.Focus();

            }
            catch (Exception)
            {


            }

        }


        private void TaskRegion_EnterSearchEvent(object sender, KeyEventArgs e)
        {
            if (String.IsNullOrEmpty(taskRegion.SearchText))
                return;

            LoadChromeUrl(myTab.ActiveTab.myBlinkBrowser, taskRegion.SearchText);
        }

        /// <summary>
        /// 加载网页
        /// </summary>
        /// <param name="mblinkBrowser"></param>
        private void LoadChromeUrl(MiniblinkBrowser mblinkBrowser, string url)
        {
            if (String.IsNullOrEmpty(url))
                return;

            if (!url.Contains("http://") && !url.Contains("https://"))
            {
                taskRegion.SearchText = "http://" + url;
                url = "http://" + url;
            }

            mblinkBrowser.LoadUri(url);
        }

        /// <summary>
        /// 点击最大化按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormStyleControl_ClickMaxEvent(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                formStyleControl.TabMaxImage = Resource.form_max;
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                formStyleControl.TabMaxImage = Resource.form_recovery;
                this.WindowState = FormWindowState.Maximized;
            }
        }

        void mouse_OnMouseActivity(object sender, MouseEventArgs e)
        {
            //int x = this.Location.X + formStyleControl.Location.X;
            //int y = this.Location.Y + formStyleControl.Location.Y;
            //Rectangle formRect = new Rectangle(new Point(x, y), formStyleControl.Size);
            //if (!formRect.Contains(e.Location))
            //{
            //    LeaveFormEvent();
            //}

            收藏
            //var rectCollection = taskRegion.GetControlLocation("taskBtn_File");
            //int collectionX = this.Location.X + rectCollection.X;
            //int collectionY = this.Location.Y + rectCollection.Y;
            //Rectangle collectionRect = new Rectangle(new Point(collectionX, collectionY), rectCollection.Size);
            //if (!collectionRect.Contains(e.Location))
            //{
            //    taskRegion.SetCollectionBackColor();
            //}

            刷新
            //var rectRefresh = taskRegion.GetControlLocation("taskBtn_Refresh");
            //int refreshX = this.Location.X + rectRefresh.X;
            //int refreshY = this.Location.Y + rectRefresh.Y;
            //Rectangle refreshRect = new Rectangle(new Point(refreshX, refreshY), rectRefresh.Size);
            //if (!refreshRect.Contains(e.Location))
            //{
            //    taskRegion.SetRefreshBackColor();
            //}
        }

        private void LeaveFormEvent()
        {
            formStyleControl.SetBackColor();
        }

        private void SetStyles()
        {
            SetStyle(
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.OptimizedDoubleBuffer |
                ControlStyles.ResizeRedraw |
                ControlStyles.DoubleBuffer, true);
            //强制分配样式重新应用到控件上
            UpdateStyles();
            base.AutoScaleMode = AutoScaleMode.None;
        }

        #region 移动窗体的dll

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        #endregion

        //移动窗体
        protected override void OnMouseDown(MouseEventArgs e)
        {
            //释放鼠标焦点捕获
            Win32.ReleaseCapture();
            //向当前窗体发送拖动消息
            Win32.SendMessage(this.Handle, 0x0112, 0xF011, 0);
            base.OnMouseUp(e);

            base.OnMouseDown(e);
        }

        private void myTab_MouseDownEvent(object sender, MouseEventArgs e)
        {
            OnMouseDown(e);
        }

        private void Chrome_Load(object sender, EventArgs e)
        {
            Register();
        }

        private void formStyleControl_ClickCloseEvent(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void contextMenuStrip_Fav_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string name = e.ClickedItem.Text;
            var list = favoriteModels.Where(s => s.Title.Contains(name)).ToList();
            if (list == null)
            {
                return;
            }
            if (list.Count() > 0)
            {
                var data = list.First();
                taskRegion.SearchText = data.Url;
                myTab.ActiveTab.myBlinkBrowser.LoadUri(data.Url);
                this.Refresh();
            }
        }

        /// <summary>
        /// 是否显示前进后退
        /// </summary>
        private void ShowForwardAndBack()
        {
            var tab = myTab.ActiveTab;
            if (tab == null)
                return;

            if (tab.myBlinkBrowser == null)
                return;

            taskRegion.IsBackPage = tab.myBlinkBrowser.CanGoBack;
            taskRegion.IsForwardPage = tab.myBlinkBrowser.CanGoForward;
            taskRegion.Refresh();
        }

        private void myTab_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void Chrome_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F12)
            {
                //myTab.ActiveTab.myBlinkBrowser.ShowDevTools();
                // blinkBrowser.ShowDevTools();
            }
        }
    }
}

以上就是C#基于Miniblink控件编写一个简易的浏览器的详细内容,更多关于C# Miniblink浏览器的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文