blazorblazor-webassemblyfluent-ui

FluentUI: Capture KeyCode [Ctrl] + Mouseclick


I am using FluentUI for Blazor WASM in version 4.10.3.

I want to check if they key [Ctrl] is pressed when clicking on an element with my mouse. I registered builder.Services.AddFluentUIComponents(); in Program.cs and added <FluentKeyCodeProvider /> in my MainLayout.razror, all accoring to documentation: https://www.fluentui-blazor.net/KeyCode.

However I can only recognize if I press [Ctrl] with another key, e.g. [Ctrl] + [G]. A single [Ctrl] KeyDown isn't recognized. For example the following does not trigger, when just pressing [Ctrl]:

public async Task OnKeyDownAsync(FluentKeyCodeEventArgs args)
{
    if (args.CtrlKey)
    {
        _logger.LogInformation("[Ctrl] was pressed.");
    }
}

How can I achieve to recognize if [Ctrl] is pressed, when clicking with my mouse (normal left click) anywhere on my page, e.g. on a div container?


Solution

  • As @Tiny Wang mentioned in the comments, the blazor built in MouseEventArgs does the trick here.

    While I can use FluentKeyCodeEventArgs for commands like [CTRL] + [Z]:

    public async Task OnKeyDownAsync(FluentKeyCodeEventArgs args)
    {
        if (args.CtrlKey && args.Key == KeyCode.KeyZ)
        {
            _logger.LogInformation("[Ctrl] + [Z]");
        }
    }
    

    For mouse clicks the blazor native MouseEventArgs should be used, for example

    <div style="background-color:blueviolet" @onclick="args => MouseClickTest(args)">Click me with [Ctrl]</div>
    
    ...
    
    private async Task MouseClickTest(MouseEventArgs mouseEventArgs)
    {
        if (mouseEventArgs.CtrlKey)
        {
            _logger.LogInformation("[Ctrl] + mouse click");
        }
    }