Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle a right click event in Blazor (client side/WASM) without showing the typical browser context menu?

HandleClick seems to only handle left clicks, but it looks like I can use onmouseup and the MouseEventArgs.Button property to detect the right click.
The problem is that the typical browser-provided context menu comes up. Is there a way to prevent that? I don't see anything like preventDefault() in Blazor.

Update: apparently we can do @onmouseup:preventDefault but the context menu still shows

like image 456
Scott Reece Avatar asked Jan 24 '20 15:01

Scott Reece


3 Answers

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.

like image 168
Scott Reece Avatar answered Dec 28 '22 17:12

Scott Reece


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");
    }
}
like image 21
oiBio Avatar answered Dec 28 '22 15:12

oiBio


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

like image 31
Scott Avatar answered Dec 28 '22 15:12

Scott