Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created February 19, 2024 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emoacht/203449ace90a230201e573c5d3480410 to your computer and use it in GitHub Desktop.
Save emoacht/203449ace90a230201e573c5d3480410 to your computer and use it in GitHub Desktop.
Find input devices.
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static class InputDeviceHelper
{
[DllImport("User32", SetLastError = true)]
private static extern uint GetRawInputDeviceList(
[Out] RAWINPUTDEVICELIST[]? pRawInputDeviceList,
ref uint puiNumDevices,
uint cbSize);
[StructLayout(LayoutKind.Sequential)]
private struct RAWINPUTDEVICELIST
{
public IntPtr hDevice;
public DeviceType dwType;
}
public enum DeviceType : uint
{
/// <summary>
/// The device is a mouse.
/// </summary>
RIM_TYPEMOUSE = 0,
/// <summary>
/// The device is a keyboard.
/// </summary>
RIM_TYPEKEYBOARD = 1,
/// <summary>
/// The device is an HID that is not a keyboard and not a mouse.
/// </summary>
RIM_TYPEHID = 2
}
public static void FindDevices()
{
uint deviceListCount = 0;
uint rawInputDeviceListSize = (uint)Marshal.SizeOf<RAWINPUTDEVICELIST>();
if (GetRawInputDeviceList(
null,
ref deviceListCount,
rawInputDeviceListSize) == 0)
{
var devices = new RAWINPUTDEVICELIST[deviceListCount];
if (GetRawInputDeviceList(
devices,
ref deviceListCount,
rawInputDeviceListSize) == deviceListCount)
{
foreach (var device in devices)
{
Trace.WriteLine($"Handle: {device.hDevice} Type: {device.dwType}");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment