CoreWebView2.ContextMenuRequested Event
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
ContextMenuRequested is raised when a context menu is requested by the user and the content inside WebView hasn't disabled context menus.
public event EventHandler<Microsoft.Web.WebView2.Core.CoreWebView2ContextMenuRequestedEventArgs> ContextMenuRequested;
member this.ContextMenuRequested : EventHandler<Microsoft.Web.WebView2.Core.CoreWebView2ContextMenuRequestedEventArgs>
Public Custom Event ContextMenuRequested As EventHandler(Of CoreWebView2ContextMenuRequestedEventArgs)
void WebView_ContextMenuRequested(
object sender,
CoreWebView2ContextMenuRequestedEventArgs args)
{
IList<CoreWebView2ContextMenuItem> menuList = args.MenuItems;
CoreWebView2ContextMenuTargetKind context = args.ContextMenuTarget.Kind;
// Using custom context menu UI
if (context == CoreWebView2ContextMenuTargetKind.SelectedText)
{
CoreWebView2Deferral deferral = args.GetDeferral();
args.Handled = true;
ContextMenu cm = new ContextMenu();
cm.Closed += (s, ex) => deferral.Complete();
PopulateContextMenu(args, menuList, cm);
cm.IsOpen = true;
}
// Remove item from WebView context menu
else if (context == CoreWebView2ContextMenuTargetKind.Image)
{
/// removes the last item in the collection
menuList.RemoveAt(menuList.Count - 1);
}
// Add item to WebView context menu
else if (context == CoreWebView2ContextMenuTargetKind.Page)
{
// Created context menu items should be reused.
if (displayUriParentContextMenuItem == null)
{
CoreWebView2ContextMenuItem subItem =
_iWebView2.CoreWebView2.Environment.CreateContextMenuItem(
"Display Page Uri", null,
CoreWebView2ContextMenuItemKind.Command);
subItem.CustomItemSelected += delegate (object send, Object ex)
{
string pageUrl = args.ContextMenuTarget.PageUri;
System.Threading.SynchronizationContext.Current.Post((_) =>
{
MessageBox.Show(pageUrl, "Display Page Uri", MessageBoxButton.YesNo);
}, null);
};
displayUriParentContextMenuItem =
_iWebView2.CoreWebView2.Environment.CreateContextMenuItem(
"New Submenu", null,
CoreWebView2ContextMenuItemKind.Submenu);
IList<CoreWebView2ContextMenuItem> submenuList = displayUriParentContextMenuItem.Children;
submenuList.Insert(0, subItem);
}
menuList.Insert(menuList.Count, displayUriParentContextMenuItem);
}
}
The host has the option to create their own context menu with the information provided in the event or can add items to or remove items from WebView context menu. If the host doesn't handle the event, WebView will display the default context menu.