Live Chat Icon For mobile
Live Chat Icon

How do I capture a browser KeyPress event in a Blazor server-side app and perform certain hotkey functions?

Platform: Blazor| Category: Event handling

To detect a browser keypress event, set the @onkeypress event to the corresponding element. For hotkey functions, you can use the event arguments to check whether the Ctrl, Shift, or Alt key is pressed.

[Index.razor]

@page "/"

<input type="text" @onkeypress="KeyboardEventHandler" />

<h4>@KeyPressed</h4>

@code {
    string KeyPressed = string.Empty;
    bool IsShiftKey;
    private void KeyboardEventHandler(KeyboardEventArgs args)
    {
        if (args.ShiftKey || args.CtrlKey || args.AltKey)
        {
            // Do some hotkey function process here
        }
        else
        {
            KeyPressed = "Key Pressed is " + args.Key;
        }
    }
}

For more information on this topic, check this documentation.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.