C# 关于浏览器——CefSharp篇

最近要写一个浏览器包裹一个网站,试了各种浏览器插件,记录一下。

CefSharp直接可以NuGet,搜索CefSharp就可以,按照你要的FrameWorks版本选择它的版本,注意项目不可以是Any CPU,必须指定x86或者x64。

测试这个效果还可以,就最终用了它,设计界面如下:

C# 关于浏览器——CefSharp篇_第1张图片

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using CefSharp;
using CefSharp.WinForms;
using System.IO;

namespace casicloud
{
    [System.Runtime.InteropServices.ComVisible(true)]
    public partial class mainForm : Form
    {
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        private const int VM_NCLBUTTONDOWN = 0XA1;//定义鼠标左键按下
        private const int HTCAPTION = 2;     
        private string cachePath=Directory.GetCurrentDirectory() + @"\cache";
        private ChromiumWebBrowser browser = null;

        public mainForm()
        {
            if (setting.getProperty("NEEDCLEANCACHE").Equals("1"))
            {
                DirectoryInfo dir = new DirectoryInfo(cachePath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        try
                        {
                            subdir.Delete(true);
                        }
                        catch
                        {

                        }
                    }
                    else
                    {
                        try
                        {
                            File.Delete(i.FullName);
                        }
                        catch
                        {

                        }
                    }
                }
                setting.setProperty("WebBrowser", "NEEDCLEANCACHE", "0");
            }

            InitializeComponent();

            var settings = new CefSettings();
            settings.CachePath = cachePath;
            //settings.CefCommandLineArgs.Add("disable-gpu", "1");
            //settings.CefCommandLineArgs.Add("no-proxy-server", "1");
            //settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required";
            settings.CefCommandLineArgs.Add("enable-media-stream", "1");
            settings.Locale = "zh-CN";
            Cef.Initialize(settings);

            this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
        }

        private void Form1_Load(object sender, EventArgs e)
        {           
            browser = new CefSharp.WinForms.ChromiumWebBrowser("http://localhost");
            browser.ContextMenuStrip = contextMenu;
            browser.LifeSpanHandler = new OpenPageSelf();
            browser.MenuHandler = new MenuHandler();
            browser.Dock = DockStyle.Fill;
            browsePanel.Controls.Add(browser);
        }        

        //系统设置
        private void MainMenu_System_Setup_Click(object sender, EventArgs e)
        {
            setup setupWin = new setup();
            setupWin.ShowDialog();
        }        

        //退出系统
        private void MainMenu_System_Quit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void MainMenu_Option_Forward_Click(object sender, EventArgs e)
        {
            browser.Forward();
        }

        private void MainMenu_Option_Back_Click(object sender, EventArgs e)
        {
            browser.Back();
        }

        private void MainMenu_Option_Refresh_Click(object sender, EventArgs e)
        {
            browser.Reload(true);
        }        

        //退出时释放对象
        private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                browser.Dispose();
                browser = null;
                CefSharp.Cef.Shutdown();
            }
            catch
            {

            }
        }

        private void MainMenu_Option_Clean_Click(object sender, EventArgs e)
        {
            //清理缓存
            Cef.GetGlobalCookieManager().DeleteCookiesAsync("","");
            setting.setProperty("WebBrowser", "NEEDCLEANCACHE","1");

            if (MessageBox.Show("部分缓存文件需要重新启动后删除,是否马上重启?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Application.Exit();
                System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
            }            
        }

        private void toolStrip1_Paint(object sender, PaintEventArgs e)
        {
            if ((sender as ToolStrip).RenderMode == ToolStripRenderMode.System)
            {
                Rectangle rect = new Rectangle(0, 0, this.toolStrip1.Width, this.toolStrip1.Height - 2);
                e.Graphics.SetClip(rect);
            }
        }

        private void menuStrip1_Paint(object sender, PaintEventArgs e)
        {
            Rectangle rect = new Rectangle(0, 0, this.menuStrip1.Width, this.menuStrip1.Height - 2);
            e.Graphics.SetClip(rect);
        }

        private void panel2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
                this.WindowState = FormWindowState.Normal;
            else
                this.WindowState = FormWindowState.Maximized;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
                this.WindowState = FormWindowState.Normal;
            else
                this.WindowState = FormWindowState.Maximized;
        }

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

        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            //为当前应用程序释放鼠标捕获
            ReleaseCapture();
            //发送消息 让系统误以为在标题栏上按下鼠标
            SendMessage((IntPtr)this.Handle, VM_NCLBUTTONDOWN, HTCAPTION, 0);
        }

        private void Button_Option_Home_Click(object sender, EventArgs e)
        {
            browser.Load("http://localhost");
        }

        //代码结束
    }
}

/// 
/// 在自己窗口打开链接
/// 
internal class OpenPageSelf : ILifeSpanHandler
{
    public bool DoClose(IWebBrowser browserControl, IBrowser browser)
    {
        return false;
    }

    public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
    {

    }

    public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
    {

    }

    public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl,
string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, 
IWindowInfo windowInfo, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
    {
        newBrowser = null;
        var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
        chromiumWebBrowser.Load(targetUrl);
        return true;
    }    
}

/// 
/// 禁用右键菜单
/// 
internal class MenuHandler : IContextMenuHandler
{

    public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser,
IFrame frame, IContextMenuParams parameters, IMenuModel model)
    {
        model.Clear();
        model.AddItem((CefMenuCommand)26501, "前进");
        model.AddItem((CefMenuCommand)26502, "后退");
        model.AddSeparator();//添加分隔符
        model.AddItem((CefMenuCommand)26503, "刷新");
    }

    public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame,
IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
    {
        if (commandId == (CefMenuCommand)26501)
        {
            browser.GoForward();
            return true;
        }
        if (commandId == (CefMenuCommand)26502)
        {
            browser.GoBack();
            return true;
        }
        if (commandId == (CefMenuCommand)26503)
        {
            browser.Reload(true);
            return true;
        }
        return false;
    }

    public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
    {

    }

    public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser,
IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
    {
        return false;
    }
}

这个代码有几个功能:

1、无边框,可拖动什么的,主要是原始窗口太丑,然后菜单什么的还有个白框,都改写了Paint;

2、禁止它的默认菜单,加了自定义菜单项(internal class MenuHandler);

3、全部在新窗口打开(internal class OpenPageSelf);

坑:

不能播放Mp4视频什么的,网上花钱下载了几个编译的插件,不知道是我的水平还是对方不行,不是编译不过,就是各种报错。

还试了一个火狐内核的Geckofx,需要什么xulrunner,配了半天也没调过,各种报错,放弃了。

就是这样。

PS:部署到客户端(Win7,X64)报了一个C:\Windows\syswow64\KERNELBASE.dll的异常代码: 0xe0434352的错误,这个我这里是缺少vc_redist.x64.exe,下载VCredist 2013.x64.exe装上就好了,我用的CefSharp.WinForms.47.0.4,根据版本不同,可能需要下载不同的运行库。

你可能感兴趣的:(编程开发,c#,开发语言,后端)