RawInputSharp 是一个 C# 库,用于处理 Windows 的原始输入(Raw Input) API,它允许开发者直接访问键盘、鼠标等输入设备的底层数据。
本例介绍如何读取键盘的虚拟码以及键盘硬件信息。效果如下图:
示例中:开始是1键的按下与抬起; 然后是shift+1键的按下与抬起。
注意shift的虚拟键是16. 因为是手按的shift晚抬起:shift按下->1按下->1抬起->shift抬起。
具体实现步骤如下:
1. 通过NuGet包安装 RawInput.Sharp.
2. 实际代码如下:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.SourceInitialized += MainWindow_SourceInitialized;
}
private void MainWindow_SourceInitialized(object sender, EventArgs e)
{
var windowInteropHelper = new WindowInteropHelper(this);
var hwnd = windowInteropHelper.Handle;
// Get the devices that can be handled with Raw Input.
var devices = RawInputDevice.GetDevices();
var keyboards = devices.OfType<RawInputKeyboard>();
foreach (var item in keyboards)
{
Console.WriteLine(item.DevicePath);
}
// register the keyboard device and you can register device which you need like mouse
RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.ExInputSink, hwnd);
HwndSource source = HwndSource.FromHwnd(hwnd);
source.AddHook(Hook);
}
private IntPtr Hook(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
{
const int WM_INPUT = 0x00FF;
try
{
// You can read inputs by processing the WM_INPUT message.
if (msg == WM_INPUT)
{
// Create an RawInputData from the handle stored in lParam.
var data = RawInputData.FromHandle(lparam);
// You can identify the source device using Header.DeviceHandle or just Device.
var sourceDeviceHandle = data.Header.DeviceHandle;
var sourceDevice = data.Device;
// The data will be an instance of either RawInputMouseData, RawInputKeyboardData, or RawInputHidData.
// They contain the raw input data in their properties.
switch (data)
{
case RawInputKeyboardData keyboard:
if (keyboard.Device == null || keyboard.Device.DevicePath == null)
{
break;
}
Console.WriteLine(keyboard.Device.DevicePath + "----" + keyboard.Keyboard);
break;
}
}
}
catch (Exception ex)
{
;
}
return IntPtr.Zero;
}
}