28 April 2024

onkeydown, onkeyup with Blazor RenderTreeBuilder

As for my desktop application, I had to find a solution to create a copy function when drag-and-dropping while holding the CTRL key. In my Blazor Server application, the component is complex and it is created via the RenderTreeBuilder. Here is the result :

 

Giving focus to the DIV with tabIndex

Here each task in the schedule is a DIV tag. So we must not forget to add the attribute TabIndex to our DIV tag. Without that, no result! :

<div tabindex="1">...</div>

What will give with RenderTreeBuilder :

builder.AddAttribute(++subseq, "tabindex", subseq);

Parameters of our component

Capturing keyboard input events is finally simple. We have at our disposal the 3 events classified in the order :

  • onkeydown
  • onkeypress
  • onkeyup

⚠ But beware, in my case I need to detect that the CONTROL key is pressed. The onkeypress event is not fired for all keys (e.g. ALT, SHIFT, and ESC). It is then appropriate to use the onkeydown event.

So I will add these two parameters to my component :

[Parameter]
public EventCallback OnKeyDown { get; set; }
[Parameter]
public EventCallback OnKeyUp { get; set; }

You will notice that I chose to return a boolean on OnKeyDown ; Indeed in my case, I want to know if CTRL is pushed in. Now I just have to attach to my DIV tag the events onkeydown and onkeyup to capture the keys of the keyboard. With the argument KeyboardEventArg we will be able to see which key is typed :

[Parameter]
builder.AddAttribute(++subseq, "onkeydown",
EventCallback.Factory.Create(
this, TaskOnKeyDown
)
);
builder.AddAttribute(++subseq, "onkeyup",
EventCallback.Factory.Create(
this, TaskOnKeyUp
)
);

And to trigger the event :

private async Task TaskOnKeyDown(KeyboardEventArgs args)
{
await OnKeyDown.InvokeAsync(args.CtrlKey);
}

Here in my case, I get a boolean telling me if CTRL is pressed. I invite you to look at what KeyboardEventArgs can return because there are some interesting things like :

  • key (la touche)
  • ShiftKey (boolean)
  • AltKey (boolean)

And of course it gives the result of combined keys like here where I press SHIFT+F :

Leave a Reply