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

 更新时间:2024年01月31日 10:30:25   作者:搬砖的诗人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浏览器的资料请关注脚本之家其它相关文章!

相关文章

  • C#获取本机IP地址(ipv4)

    C#获取本机IP地址(ipv4)

    本文主要介绍了C#获取本机所有IP地址的方法、C#获取本机IP地址(ipv4)的方法等。具有很好的参考价值。下面跟着小编一起来看下吧
    2017-03-03
  • C#实现读写ini文件类实例

    C#实现读写ini文件类实例

    这篇文章主要介绍了C#实现读写ini文件类,实例分析了C#实现针对ini文件的读、写、删除等操作的常用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-03-03
  • C#操作SQLite数据库方法小结

    C#操作SQLite数据库方法小结

    这篇文章介绍了C#操作SQLite数据库的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • Visual Studio 2019 清理空行问题(非正则表达式)

    Visual Studio 2019 清理空行问题(非正则表达式)

    这篇文章主要介绍了Visual Studio 2019 清理空行问题(非正则表达式),本文通过实例截图给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-04-04
  • C#中验证sql语句是否正确(不执行语句)

    C#中验证sql语句是否正确(不执行语句)

    C#中验证sql语句是否正确(不执行语句),需要的朋友可以参考一下
    2013-03-03
  • 使用C#中的Flags特性

    使用C#中的Flags特性

    这篇文章介绍了使用C#中的Flags特性,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-07-07
  • C#中循环语句:while、for、foreach的使用

    C#中循环语句:while、for、foreach的使用

    本篇文章主要介绍了C#中的三种循环语句(while、for、foreach)的实现方式,需要的朋友可以参考下
    2015-07-07
  • C#设置或验证PDF文本域格式的方法详解

    C#设置或验证PDF文本域格式的方法详解

    PDF中的文本域可以通过设置不同格式,用于显示数字、货币、日期、时间、邮政编码、电话号码和社保号等等。本文将介绍如何通过C#设置或验证PDF文本域格式,需要的可以参考一下
    2022-01-01
  • C#在MySQL大量数据下的高效读取、写入详解

    C#在MySQL大量数据下的高效读取、写入详解

    最近由于工作的原因,经常需要对海量数据进行处理,做的数据爬虫相关,动辄千万级别的数据,单表几十个G 都是都是家常便饭。 那么主要的开发语言是C#,数据库使用的是MySQL。下面通过这篇文章我们来一起学习学习吧。
    2016-11-11
  • C# 复制与删除文件的实现方法

    C# 复制与删除文件的实现方法

    这篇文章主要介绍了C# 复制与删除文件的实现方法的相关资料,希望通过本文能帮助到大家,让大家理解掌握这部分内容,需要的朋友可以参考下
    2017-10-10

最新评论