How do you disable the right-click context menu in the Chromium Web Browser using C#?
I found this Disable context menu in Chromium Embedded 3 (DCEF3) but I'm not familiar with the syntax (I'm using C#), plus I don't see an event on the CefSharp.WinForms.ChormiumWebBrowser class called OnBeforeContextMenu.
I faced the same problem but the above solution could no longer be used since the interface IMenuHandler
(renamed to IContextMenuHandler
) has had a few changes and there no longer exists
bool OnBeforeContextMenu(IWebBrowser browser);
which has the following signature now:
void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model);
The SO question linked in the question (Disable context menu in Chromium Embedded 3 (DCEF3)) has to do with pascal and inno setup script but the accepted answer adjusted for C# and ChromiumWebBrowser
worked for me. The solution is to clear the model parameter in the implementation of OnBeforeContextMenu
. The implementation of IContextMenuHandler
can look like this:
public class CustomContextHandler : IContextMenuHandler
{
public void OnBeforeContextMenu(IWebBrowser browserControl, CefSharp.IBrowser browser, IFrame frame, IContextMenuParams parameters,
IMenuModel model)
{
model.Clear();
}
public bool OnContextMenuCommand(IWebBrowser browserControl, CefSharp.IBrowser browser, IFrame frame, IContextMenuParams parameters,
CefMenuCommand commandId, CefEventFlags eventFlags)
{
return false;
}
public void OnContextMenuDismissed(IWebBrowser browserControl, CefSharp.IBrowser browser, IFrame frame)
{
}
}
Then in the code that creates an object of the chromium web browser:
browser = new ChromiumWebBrowser(url);
browser.MenuHandler = new CustomContextHandler();
Ok I was able to figure this out. The problem with the article referenced in my original question is that it uses the Chromium Embedded component. I'm not using that. I'm using the cefsharp chromium web browser. To hide the right-click context menu I found the answer in this article: https://github.com/cefsharp/CefSharp/issues/107
You just have to define a class that implements the IMenuHandler interface, then set the browser control MenuHandler property to this class. Finally in the class return a FALSE in the OnBeforeContextMenu method. Here is the class:
public class CustomMenuHandler : IMenuHandler
{
public bool OnBeforeContextMenu(IWebBrowser browser)
{
return false;
}
}
Next, set the instance of the Chromium web browser's MenuHandler property to this class:
var browser = new ChromiumWebBrowser(string.empty);
browser.MenuHandler = new CustomMenuHandler();
Worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With