If you know how to work with CefSharp and you've already implemented it on one of your awesome projects, then you know what is and how it looks the context menu:
Although we already write about how to add new options to the context menu on a CefSharp control, sometimes you would simply like to remove the context menu to prevent any problem in your app. In this article we'll explain you how to achieve it easily.
Important note
This snippet is very friendly and useful if you use a custom HTML/JavaScript/CSS context menu on your application instead, because the HTML based context menu (on your JS application) will still work !
1. Create a custom Menu Handler
Create a new class on your project namely MyCustomMenuHandler
(you can change the name if you want).This class needs to use the namespace of your application and extend the IContextMenuHandler
, therefore you should obviously import the CefSharp namespace into your class.
This interface exposes the following 4 members that need to obviously be declared (even empty), otherwise you'll face the exception on your code "Doesn't implement member etc.":
using CefSharp;
public class MyCustomMenuHandler : IContextMenuHandler
{
public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
{
model.Clear();
}
public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
{
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;
}
}
Once the class is available on your project, then proceed with the step 2 to register your custom context menu handler.
2. Set your custom Menu Handler as default on the browser
Finally, you only need to set the value of the MenuHandler
property of your ChromiumWebBrowser
as a new instance of your custom menu handler and the context menu shouldn't appear anymore. This can be achieved during the creation of the browser in your current code, for example:
CefSettings settings = new CefSettings();
// Some settings if you have, here
// Initialize cef with the provided settings
Cef.Initialize(settings);
// Create a browser component
ChromiumWebBrowser chromeBrowser = new ChromiumWebBrowser("www.somewebsite or file.com");
// Register your Custom Menu Handler as default
chromeBrowser.MenuHandler = new MyCustomMenuHandler();
// ...
// Rest of your code
// ...
As mentioned previously, this solution is really great if you still want to allow that you application has a custom context menu, however made with JavaScript (but doesn't exist necessarily).
Happy coding !