问题描述
我希望能够在不使用 Blazor 中的 HTML INPUT 标记的情况下捕获键盘输入.按下该键后,我将显示一个图形来表示按下的字母.
类似的东西
@page "/counter"@using Microsoft.AspNetCore.Components.Web<div @onkeypress="e => KeyPress(e)">按任意字母键
我希望能够在不使用 Blazor 中的 HTML INPUT 标记的情况下捕获键盘输入.按下该键后,我将显示一个图形来表示按下的字母.
类似的东西
@page "/counter"@using Microsoft.AspNetCore.Components.Web<div @onkeypress="e => KeyPress(e)">按任意字母键
@代码 {private void KeyPress(KeyboardEventArgs e){var 字母 = e.Key;}}
当我在 KeyPress 方法上设置断点时,它似乎没有被调用.非常感谢任何帮助.
你快到了,但你忘了让 div 成为焦点.这是步骤:
0.- 添加 tabindex
标签使您的 div 可聚焦:
<div类=大屏幕"@onkeydown="@KeyDown"标签索引=0"@ref="myDiv" ><h1 class="display-4">@信
1.- 在 _Host.cshtml
上创建一个 js 代码来设置焦点到你的 div,例如:
该函数将一个 Element 引用作为参数.
2.- 在您的组件呈现后调用此函数.
受保护的元素引用 myDiv;//由@ref 属性设置受保护的异步覆盖任务 OnAfterRenderAsync(bool firstRender){如果(第一次渲染){等待 JSRuntime.InvokeVoidAsync("SetFocusToElement", myDiv);}}
3.- 实现你自己的KeyDown
:
protected void KeyDown(KeyboardEventArgs e){letter = $"按下:[{e.Key}]";}
请注意,这不是 Blazor 问题,只是默认的 html 和 js 行为.我学会了编写游戏,请在
2019 年 11 月
由 @Quango 改进的代码(非常感谢)
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.
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:
Demo at Flappy Blazor Bird
Edited Nov 2019:
Code improved by @Quango (many thanks)
这篇关于如何在不使用 Blazor 中的输入标签的情况下检测按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!