Code Monkey home page Code Monkey logo

rawinput-sharp's Introduction

RawInput.Sharp

A simple wrapper library for Windows Raw Input. Available on .NET Standard 1.1 and .NET Framework 4.6.1.

NuGet

https://www.nuget.org/packages/RawInput.Sharp/

Usage

Acquiring connected devices

// using Linearstar.Windows.RawInput;

// Get the devices that can be handled with Raw Input.
var devices = RawInputDevice.GetDevices();

// Keyboards will be returned as RawInputKeyboard.
var keyboards = devices.OfType<RawInputKeyboard>();

// Mice will be RawInputMouse.
var mice = devices.OfType<RawInputMouse>();

Reading raw inputs

protected override void WndProc(ref Message m)
{
    const int WM_INPUT = 0x00FF;

    // You can read inputs by processing the WM_INPUT message.
    if (m.Msg == WM_INPUT)
    {
        // Create an RawInputData from the handle stored in lParam.
        var data = RawInputData.FromHandle(m.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 RawInputMouseData mouse:
                Console.WriteLine(mouse.Mouse);
                break;
            case RawInputKeyboardData keyboard:
                Console.WriteLine(keyboard.Keyboard);
                break;
            case RawInputHidData hid:
                Console.WriteLine(hid.Hid);
                break;
        }
    }

    base.WndProc(ref m);
}

Further examples

License

zlib License

rawinput-sharp's People

Contributors

argogulskii avatar joosthoi2 avatar lindexi avatar mfakane avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

rawinput-sharp's Issues

DigitizerExample only lists two finger contacts

I tried DigitizerExample. It only lists two finger contact even if I used more than two fingers on the screen. (I'm trying on a device which is equipped with multi-touch (upto 10 fingers) and pen capability. Would this be a bug? Is there a chance to fix this?
Best Regards,

Only first lbuttonDown received on repeat press

I modified the sample to receive mouse event also

 class Program
    {
        static void Main()
        {
            // Get the devices that can be handled with Raw Input.
            var devices = RawInputDevice.GetDevices();

            // Keyboards will be returned as a RawInputKeyboard.
            var keyboards = devices.OfType<RawInputKeyboard>();

            // List them up.
            foreach (var device in keyboards)
                Console.WriteLine($"{device.DeviceType} {device.VendorId:X4}:{device.ProductId:X4} {device.ProductName}, {device.ManufacturerName}");

            // Mice will be RawInputMouse.
            var mice = devices.OfType<RawInputMouse>();
            foreach (var mouse in mice)
                Console.WriteLine($"{mouse.DeviceType} {mouse.VendorId:X4}:{mouse.ProductId:X4} {mouse.ProductName}, {mouse.ManufacturerName}");

            // To begin catching inputs, first make a window that listens WM_INPUT.
            var window = new RawInputReceiverWindow();

            window.Input += (sender, e) =>
            {
                // Catch your input here!
                var data = e.Data;

                Console.WriteLine(data);
            };

            try
            {
                // Register the HidUsageAndPage to watch any device.
                RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.ExInputSink | RawInputDeviceFlags.NoLegacy, window.Handle);
                RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.ExInputSink | RawInputDeviceFlags.NoLegacy, window.Handle);

                Application.Run();
            }
            finally
            {
                RawInputDevice.UnregisterDevice(HidUsageAndPage.Keyboard);
                RawInputDevice.UnregisterDevice(HidUsageAndPage.Mouse);
            }
        }
    }

If i press the lbutton down repeatedly only first event is received. Rest of the LButton events are received after pressing any other keyboard key or rbutton. How can the subsequent lbutton keys be received immediately? All other keys work fine.

ArgumentException at RawInputDigitizerContact constructor with TouchPad

Thank you for great library! It is really useful to get inputs from HID devices.

I have tested it to parse inputs from Precision TouchPad (PTP) and encountered System.ArgumentException (HResult=0x80070057
Message=An item with the same key has already been added.) at RawInputDigitizerContact constructor when a window receives WM_INPUT message. They are fired at following two Enumerable.ToDictionary methods.

var buttons = buttonStates.ToDictionary(x => x.Button.UsageAndPage, x => x.IsActive);
var values = valueStates.ToDictionary(x => x.Value.UsageAndPage);

This exception is relatively common in Enumerable.ToDictionary method when there are duplicate keys. It is not difficult to avoid this exception and I will be happy to send PR to fix this issue.

Before start working, I would like to hear your view on this issue especially whether the first value or the last value is to be preserved. I have no strong view on this selection.

Duplicated HashCode of HidUsageAndPage

code link:

public override int GetHashCode() =>

here's my test using this code:

        public override int GetHashCode()
        {
            var hashcode = typeof(HidUsageAndPage).GetHashCode() ^
UsagePage.GetHashCode() ^
Usage.GetHashCode();

            Debug.WriteLine($"UsagePage:{UsagePage}, Usage:{Usage}, HashCode:{hashcode}");

            return hashcode;
        }

the output (please check lines with arrow):

UsagePage:13, Usage:60, HashCode:30015907
UsagePage:13, Usage:69, HashCode:30015962
UsagePage:13, Usage:68, HashCode:30015963
UsagePage:13, Usage:66, HashCode:30015965
UsagePage:13, Usage:50, HashCode:30015917
UsagePage:1, Usage:49, HashCode:30015906   <----
UsagePage:1, Usage:48, HashCode:30015907
UsagePage:13, Usage:48, HashCode:30015919
UsagePage:13, Usage:62, HashCode:30015905
UsagePage:13, Usage:61, HashCode:30015906  <----
UsagePage:1, Usage:49, HashCode:30015906  <----
UsagePage:13, Usage:61, HashCode:30015906  <----

You can see diffent UsagePage and Usage returned same value.

Cannot open game controller for raw input

Hi @mfakane, I'm trying to use your wrapper to receive raw input from game controllers. Here's an example controller I'm trying to read:

image

I've tried to modify SimpleExample to use either HidUsageAndPage.Joystick or HidUsageAndPage.Gamepad, but there is a Win32ErrorException. RegisterRawInputDevices returns false with GetLastError = 87, which is "The parameter is incorrect.".

I also tried to directly access it like this as well:

            try
            {
                // Register the HidUsageAndPage to watch any device.
                RawInputDevice.RegisterDevice(devices[0].UsageAndPage, RawInputDeviceFlags.ExInputSink | RawInputDeviceFlags.NoLegacy, window.Handle);

                Application.Run();
            }
            finally
            {
                RawInputDevice.UnregisterDevice(devices[0].UsageAndPage);
            }

I'm not sure if it's correct, but it returns the same error. What am I supposed to do?

Crash while using Multiplicity software

When running Multiplicity KVM software users are reporting crash:

Linearstar.Windows.RawInput.Native.Win32ErrorException: Invalid access to memory location.

   at Linearstar.Windows.RawInput.Native.User32.GetRawInputDataHeader(RawInputHandle rawInput)
   at Linearstar.Windows.RawInput.RawInputData.FromHandle(RawInputHandle rawInput)
   at livelywpf.Core.RawInputDX.Hook(IntPtr hwnd, Int32 msg, IntPtr wparam, IntPtr lparam, Boolean& handled)
   at System.Windows.Interop.HwndSource.PublicHooksFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

Reference: rocksdanister/lively#575

Using in Unity

Compiling the DLL and importing it into Unity works, and I can iterate through the devices and see them, but I am confused on how to catch the raw input inside Unity using this, as I don't think overriding WndProc inside Unity is possible (since it can't use Windows.Forms). Is there a way to get the raw input in Unity?

Issue with Missing WM_INPUT Signals When Focusing on "Start Menu" in WPF

protected override void OnSourceInitialized(EventArgs e)
{
    var windowInteropHelper = new WindowInteropHelper(this);
    var hwnd = windowInteropHelper.Handle;
    var devices = RawInputDevice.GetDevices();

    RawInputDevice.RegisterDevice(HidUsageAndPage.TouchScreen,
        RawInputDeviceFlags.ExInputSink | RawInputDeviceFlags.DevNotify, hwnd);
    RawInputDevice.RegisterDevice(HidUsageAndPage.TouchPad,
        RawInputDeviceFlags.ExInputSink | RawInputDeviceFlags.DevNotify, hwnd);
    RawInputDevice.RegisterDevice(HidUsageAndPage.Pen,
        RawInputDeviceFlags.ExInputSink | RawInputDeviceFlags.DevNotify, hwnd);
    HwndSource source = HwndSource.FromHwnd(hwnd);
    source.AddHook(WndProc);
}

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    switch (msg)
    {
        case 0x00FF:
            {
                ProcessInputCommand(lParam);
                break;
            }
    }
    handled = false;
    return IntPtr.Zero;
}

Regardless of the triggering position, whenever focusing on the "Start Menu" in the system, the msg no longer receives the 0x00FF signal. Whether it's TouchScreen, TouchPad, or Pen, the issue persists. This has been bothering me for a long time. I would like to ask how to solve this problem, so that even when focusing on the "Start Menu" in the system, I can still receive the correct WM_INPUT signals. Thank you.

*My system is win11

Hook keys

Hi.

Great library, works really well. How would I go about globally hooking a key?

Joe

WndProc method triggers twice for one keystroke

Here is a sample console output.Any idea why ?

Keyboard : 100
Vendor Id: 1118
Product Id: 1970
Keyboard : 100
Vendor Id: 1118
Product Id: 1970
Keyboard : 104
Vendor Id: 1118
Product Id: 1970
Keyboard : 104
Vendor Id: 1118
Product Id: 1970

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

None detected


  • Check this box to trigger a request for Renovate to run again on this repository

Keyboard language problem

Hi,

I'm using your library to sniff barcodes from barcode reader. There is an option on barcode readers which you can change the language setting of the barcode reader.

When I read a barcode from my barcode scanner, normally it gets the right characters both rawinput and pc screen. Below image shows right scenario.

image

My problem is, if I change the language setting of my barcode scanner to Turkey, rawinput gets additional characters like below image.

image

Could you please help me about why this is happening?

Register Only Specific Devices

I have a WPF application that has one or more HID keyboard devices connected. Is there a way to register ONLY these devices (and not the regular keyboard) with RawInput? I see there is an UnregisterDevice method, but it only works for specific "types" of device; for example, I could call it like this:

RawInputDevice.UnregisterDevice(HidUsageAndPage.Keyboard);

Unfortunately, this unregisters ALL keyboard devices.

What I would like to do is loop through registered devices and Unregister those which are NOT of a specific (VendorId, ProductId). Better yet, I would like to get a list of HID devices and register ONLY devices with a specific (VendorId, ProductId).

Any ideas how I can accomplish this?

UvotGuy

HasFlag(RawKeyboardFlags.Down) alsways returns true

Like the title says, if you have a RawKeyboardFlags variable and you use HasFlag(RawKeyboardFlags.Down) on it, it will always return true, this is due to RawKeyboardFlags.Down being 0 in the enum and the bitwise logic that goes into checking if it has the flag. In flag enums this should only ever be used as a flag "everything".

In my own code I temporarily use if (flags.Equals(RawKeyboardFlags.Down) || flags.Equals(RawKeyboardFlags.LeftKey));
But it should be fixed

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.