Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

keyboard - How to detect key press without using an input tag in Blazor

I want to be able to capture keyboard input without using an HTML INPUT tag in Blazor. Once the key is pressed i will display a graphic to represent the letter pressed.

Something like this

@page "/counter"
@using Microsoft.AspNetCore.Components.Web

<div @onkeypress="e => KeyPress(e)">
    Press any letter key
</div>

@code {

    private void KeyPress(KeyboardEventArgs e)
    {
        var letter = e.Key;
    }
}

The KeyPress method does not appear to be called when I set a breakpoint on it. Any help much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are almost there, but you forgot to make div focused. This is the steps:

0.- Make your div focusable adding tabindex tag:

<div 
    class="jumbotron"
    @onkeydown="@KeyDown"
    tabindex="0"
    @ref="myDiv" >
   <h1 class="display-4">
       @letter
   </h1>   
</div>

1.- Create a js code to set focus to your div, on _Host.cshtml for example:

    <script>
        window.SetFocusToElement = (element) => {
            element.focus();
        };
    </script>

This function takes an Element reference as the parameter.

2.- Call this function after your component is rendered.


protected ElementReference myDiv;  // set by the @ref attribute

protected async override Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender) 
    {
        await JSRuntime.InvokeVoidAsync("SetFocusToElement", myDiv);
    }            
}  

3.- Implement your own KeyDown:

protected void KeyDown(KeyboardEventArgs e)
{
    letter = $"Pressed: [{e.Key}]";
}

Notice that this is not a Blazor issue, is just the default html and js behavior. I learned it writing a game, check it out at Blagario lab.

Running:

Flappy Blazor Bird

Demo at Flappy Blazor Bird

Edited Nov 2019:

Code improved by @Quango (many thanks)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...