How do I handle a right click event in Blazor (client side/WASM) without showing the typical browser context menu?
OK, I figured it out:
<div oncontextmenu="return false;" @onclick="HandleClick" @onmouseup="HandleMouseUp" >
this is a div
</div>
@code {
void HandleClick(MouseEventArgs args)
{
Console.WriteLine("This is a left click");
}
void HandleMouseUp(MouseEventArgs args)
{
if (args.Button == 2)
Console.WriteLine("This is a right click");
}
}
The key is the oncontextmenu="return false;"
javascript in the div itself.
You can use the @oncontextmenu directly in blazor. combined with @oncontextmenu:preventDefault="true" it does not show the context menu.
<div @onclick="HandleClick" @oncontextmenu="HandleRightClick" @oncontextmenu:preventDefault="true" >
this is a div
</div>
@code {
void HandleClick(MouseEventArgs args)
{
Console.WriteLine("This is a left click");
}
void HandleRightClick(MouseEventArgs args)
{
if (args.Button == 2)
Console.WriteLine("This is a right click");
}
}
Thanks for the info it helped me a lot
Just a tip for anyone using this I made my own context menu component using a div with labels for menu items and was finding the default context menu would still show up occasionally on things like a double click with the right mouse button or if I held down the right mouse button for too long. turns out the right click was happening on my menu component and then showed the default menu, as it was shown over the current mouse position. so adding the oncontextmenu="return false;" to my menu component was also required to stop it completely.
just sharing as it took me too long to figure out why it was still coming up