dotnet / dotnet/Silk.NET

How can I get a virtual key from silk input?

Open
#2,549 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
5.2k
Forks
477
Avg merge
3d 16h
Merged PRs (30d)
2

Description

# Summary
Im trying to integrate a silk window into WPF, I already have a solution to bind keyboard keys (like CTRL+K) to specific actions. The WPF inputs use the WPF Key enumeration which works fine.
I want to reuse most of that code (input handling, keybind settings, displaying in ui etc) from my current implementation because most of the app remains WPF.
So what im trying now is to convert the data i get in `KeyDown`/`KeyUp` and convert it to the WPF Keys enum.

My first approach was to just use the Silk.NET.Input.Key and translate it to the WPF enum.
However that failed because the [Key parameter is not handling localisation](https://github.com/dotnet/Silk.NET/issues/737), returning Y for the Z key on german layouts etc.

My next approach was to use the scancode and convert it to a [virtual key](https://learn.microsoft.com/de-de/windows/win32/inputdev/virtual-key-codes)
For that im converting the scancode to a virtual key which is then converted to the wpf enum using `KeyInterop.KeyFromVirtualKey`.
The `KeyInterop.KeyFromVirtualKey` works fine and i already use it in other parts of the app, the problem seems to be converting the scancode to a virtual key.
For that conversion im using this win32 functions:

```
[DllImport("user32.dll")]
private static extern IntPtr GetKeyboardLayout(uint idThread);
[DllImport("user32.dll")]
private static extern uint MapVirtualKeyEx(uint uCode, MapType uMapType, IntPtr dwhkl);
MapVirtualKeyEx(i, MapType.MAPVK_VSC_TO_VK, GetKeyboardLayout(0))
```

With that approach the problem is that keys on the numpad are not getting the correct virtual key from `MapVirtualKey` when numlock is active (ie, `Key.Home` instead of `Key.Numpad7`)

Now i could obviously build some abomination of if-else and switch-case but that seems hard to maintain and i cant verify that it fully works with all keyboards. So i was wondering what you guys are using.
How can I get a virtual key from the data silk provides in the KeyDown/Up event?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.