2

Question: I want to read gamepad/joystick input under c# and want to be able to tell which key is pressed. (at least few gamepad models)

Google and stackoverflow are full of different outdated solutions, most of them are asked in 2011. Some of the popular libraries, like SharpDX or SlimDX are already abandoned and not supported.

I end up using SharpLibHid that is messing with some raw input. And I even had some success. I am developing a WPF app, but that library requires WndProc from winforms, with help of this trick https://stackoverflow.com/a/42008211/3348804 everything works fine. The code is long and you can get great example software here: https://github.com/Slion/SharpLibHid

Point is I was able to extract this information from SharpLib.Hid.Event:

InputReport: 0000000F808080800000000000000000000000000202010200020002
DeviceInfo: ShanWan, USB WirelessGamepad 
[#Header# dwSize: 52, dwType: RIM_TYPEHID, hDevice: 65610, wParam: 1]
[#Hid# dwCount: 1, dwSizeHid: 28]
[#Keyboard# Message: 251658240, ExtraInformation: 2155905152, Flags: RI_KEY_MAKE, MakeCode: 28, VKey: 0, Reserved: 1]
[#Mouse# usButtonData: 0, usButtonFlags: RI_MOUSE_LEFT_BUTTON_DOWN, lLastX: -2139062144, lLastY: 0, ulButtons: 1, ulExtraInformation: 0, usFlags: 28, ulRawButtons: 251658240]
[KeyId: 1835008, UsageCollection: 5]
UsageValues: [015][128][128][128][128][000][000][000][000][000][000][000][000][000][000][000][000][512][512][513][514]
UsageCollectionNameAndValue: GamePad (0x0005)

By using empirical approach I can observe some patterns and use some of these data to work with gamepad. It is simply not right way to do. And for another gamepad the InputReport patterd is totally different.

I saw alot of keymapper programs for gamepads - they can understand almost any device. So there is some way to do things right.

Maybe one can suggest atleast some documentation on how to work with gamepads or how to interpret raw data (with real world examples)?

1 Answers1

-1

This is platform and framework dependent.

The only framework that fully supports this is UWP with the GamePad API.

For .NET Framework, .NET Core and .NET you need to rely on P/Invoke or custom implementation or 3rd party library. For WPF I found this.

I needed to control a Raspberry Pi RC car with an XBox One S Controller. On Linux the files that correspond to game-pads (Joysticks) are /dev/input/js[x] where x is a number (e.g. /dev/input/js0) (docs). This is considered legacy now and it is recommended to work with Linux evdev instead (docs).

There is a .NET Core library on GitHub for game-pads on Linux. It continuously reads the /dev/input/js0 file and raises events based on the data. It also consists of a working sample. Looking at the implementation will give you an idea of how to interpret raw data.

Sasan
  • 3,840
  • 1
  • 21
  • 34