How to handle mouse click in CefSharp to navigate back and forward

user3779581 picture user3779581 · Jun 26, 2014 · Viewed 8.4k times · Source

I'm using CefSharp for Windows Forms and I'm having an issue with implementing the mouse back(XButton1) and mouse forward (XButton2) event to navigate through the browsing history.

I tried the following code but the MouseClick event does not seem to be triggered:

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CefSharp.WinForms.Example
{
    public partial class BrowserForm : Form
    {
        private readonly ChromiumWebBrowser browser;

        public BrowserForm()
        {
            InitializeComponent();


            Text = "CefSharp";
            WindowState = FormWindowState.Maximized;

            browser = new ChromiumWebBrowser("http://www.google.com")
            {
                Dock = DockStyle.Fill,
            };

            browser.MenuHandler = new MenuHandler();
            browser.MouseClick += (sender, args) =>
            {
                MessageBox.Show("Button pressed: " + args.Button.ToString());

                if (args.Button.Equals(MouseButtons.XButton1))
                {

                    if (browser.CanGoBack)
                    {
                        browser.Back();
                    }
                }
                else if (args.Button.Equals(MouseButtons.XButton2))
                {
                    if (browser.CanGoForward)
                    {
                        browser.Forward();
                    }
                }
            };
            toolStripContainer.ContentPanel.Controls.Add(browser);
        }
    }
}

Answer

Professor of programming picture Professor of programming · Feb 26, 2016

I know this is an old question but I stumbled across it via Google so thought it would be worth providing an answer. If you implement IContextMenuHandler you can control the ContextMenu. The two links below demo what's required (and some other useful features).

https://github.com/cefsharp/CefSharp/blob/935d3900ba2147f4786386596b62339087ff61b0/CefSharp.WinForms.Example/Handlers/MenuHandler.cs#L15

https://github.com/cefsharp/CefSharp/blob/c18f951a97a515df112d67775c767d4222f88c23/CefSharp.WinForms.Example/BrowserTabUserControl.cs#L31