private void RegisterDevices(List <InputMapping> mappings, IntPtr windowHandle)
        {
            var devices       = RawInputDevice.GetDevices();
            var usageAndPages = new HashSet <HidUsageAndPage>();

            foreach (var device in devices)
            {
                var mapping = mappings.FirstOrDefault(x => x.ContainsDevice(device.VendorId, device.ProductId));
                if (mapping == null)
                {
                    continue;
                }

                Logging.Log(new Dictionary <string, string>
                {
                    { "VendorId", device.VendorId.ToString("X") },
                    { "ProductId", device.ProductId.ToString("X") },
                    { "DevicePath", device.DevicePath },
                    { "ConfigFile", mapping.FileName },
                }, $"Found input mapping for device {device.VendorId.ToString("X")}:{device.ProductId.ToString("X")}");

                usageAndPages.Add(device.UsageAndPage);
            }

            foreach (var usage in usageAndPages)
            {
                RawInputDevice.RegisterDevice(usage, RawInputDeviceFlags.None, windowHandle);
            }
        }
Exemple #2
0
        public static Thread MouseListenerThread(OnDeviceEvent onDeviceEventCallback, string deviceIdFilter = null)
        {
            Thread mouseListenerThread = new Thread(() =>
            {
                var mouse    = new RawInputReceiverWindow();
                mouse.Input += (sender, e) =>
                {
                    if (deviceIdFilter != e.Data.Header.DeviceHandle.ToString())
                    {
                        return;
                    }
                    onDeviceEventCallback(e.Data);
                };

                try
                {
                    // Register the HidUsageAndPage to watch any device.
                    RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.ExInputSink, mouse.Handle);
                    Application.Run();
                }
                finally
                {
                    RawInputDevice.UnregisterDevice(HidUsageAndPage.Mouse);
                }
            });

            mouseListenerThread.Priority = ThreadPriority.Highest;
            mouseListenerThread.Start();
            return(mouseListenerThread);
        }
Exemple #3
0
        private Input()
        {
            ButtonStates = new Dictionary <ButtonKind, ButtonState>()
            {
                { ButtonKind.Left, ButtonState.Off },
                { ButtonKind.Up, ButtonState.Off },
                { ButtonKind.Down, ButtonState.Off },
                { ButtonKind.Right, ButtonState.Off },
                { ButtonKind.Confirm, ButtonState.Off },
                { ButtonKind.Cancel, ButtonState.Off },
            };

            //GenBindingDictionary();
            _buttonBindings = PlayerSettings.Instance.ButtonBindings;

            var devices = RawInputDevice.GetDevices();

            foreach (var device in devices)
            {
                Logger.DebugLog($"{device.DeviceType}");
            }

            _inputQueue = new ConcurrentQueue <RawInputState>();
            new Thread(() =>
            {
                //create input window
                _window = new InputWindow();
                //subscribe to it
                _window.Input += (object sender, RawInputEventArgs e) =>
                {
                    switch (e.Data)
                    {
                    case RawInputKeyboardData kb_data:
                        Logger.DebugLog(kb_data.Keyboard.ScanCode.ToString());
                        _inputQueue.Enqueue(new RawInputState()
                        {
                            Code  = kb_data.Keyboard.ScanCode,
                            State = !kb_data.Keyboard.Flags.HasFlag(RawKeyboardFlags.Up)
                        });
                        break;

                    case RawInputMouseData m_data:
                        break;

                    case RawInputHidData h_data:

                        break;

                    default:
                        break;
                    }
                };

                //inputReceiver;
                //run the thing,,,heck
                RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.ExInputSink | RawInputDeviceFlags.NoLegacy, _window.Handle);
                Application.Run();
            }).Start();
            RebindStatus = false;
        }
        //public static void RefreshHook()
        //{
        //	receiver.Input -= RawInputReceived;
        //	receiver.DestroyHandle();
        //	receiver = new RawInputReceiverWindow();
        //	receiver.Input += RawInputReceived;
        //}

        public static void Hook(IntPtr hWnd)
        {
            // To begin catching inputs, first make a window that listens WM_INPUT.
            receiver = new RawInputReceiverWindow();

            RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.InputSink, receiver.Handle);

            receiver.Input += RawInputReceived;
        }
        public void Listen()
        {
            var hWnd = new WindowInteropHelper(Application.Current.MainWindow ?? throw new InvalidOperationException()).EnsureHandle();

            _source = HwndSource.FromHwnd(hWnd);
            _source.AddHook(WndProcHook);

            RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.InputSink, hWnd);
            RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.InputSink, hWnd);
        }
Exemple #6
0
        private void Window_SourceInitialized(object sender, EventArgs e)
        {
            var windowInteropHelper = new WindowInteropHelper(this);
            var hwnd = windowInteropHelper.Handle;

            //ExInputSink flag makes it work even when not in foreground, similar to global hook.. but asynchronous, no complications & no AV false detection!
            RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse,
                                          RawInputDeviceFlags.ExInputSink, hwnd);

            HwndSource source = HwndSource.FromHwnd(hwnd);

            source.AddHook(Hook);
        }
        private void MainWindow_Load(object sender, EventArgs e)
        {
            var flags         = RawInputDeviceFlags.InputSink;
            var handle        = Handle;
            var registrations = new RawInputDeviceRegistration[]
            {
                new RawInputDeviceRegistration(HidUsageAndPage.Keyboard, flags, handle),
                new RawInputDeviceRegistration(HidUsageAndPage.Mouse, flags, handle)
            };

            RawInputDevice.RegisterDevice(registrations);

            trayIcon.Visible = true;
        }
Exemple #8
0
    public void RegisterWindow(HwndSource source)
    {
        if (_source != null)
        {
            throw new InvalidOperationException("Cannot register more than one window");
        }

        _source = source;

        source.AddHook(MessageSink);

        RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.ExInputSink, source.Handle);
        RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.ExInputSink, source.Handle);
    }
Exemple #9
0
        private void OnEnable()
        {
            RawInputWindowProcedure.Instance.ReceiveRawInput += OnReceiveRawInput;
#if UNITY_EDITOR
            Debug.Log("RawInputDevice.RegisterDevice was skipped in editor, readWhenBackground = " + readWhenBackground);
#else
            RawInputDevice.RegisterDevice(
                HidUsageAndPage.Mouse,
                readWhenBackground
                    ? RawInputDeviceFlags.InputSink
                    : RawInputDeviceFlags.None,
                WinApiUtils.GetUnityWindowHandle()
                );
#endif
        }
        public NativeWindowInputProvider(ILogger logger, IInputService inputService)
        {
            _logger       = logger;
            _inputService = inputService;

            _sponge = new SpongeWindow();
            _sponge.WndProcCalled += SpongeOnWndProcCalled;

            _taskManagerTimer          = new System.Timers.Timer(500);
            _taskManagerTimer.Elapsed += TaskManagerTimerOnElapsed;
            _taskManagerTimer.Start();

            RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.InputSink, _sponge.Handle);
            RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.InputSink, _sponge.Handle);
        }
Exemple #11
0
        static void RegisterRawInput()
        {
            reciever = new RawInputReceiverWindow();

            var devices = RawInputDevice.GetDevices();
            var mouse   = devices.OfType <RawInputMouse>();

            reciever.Input += (sender, e) => MouseWheelScroll(e.Data);

            try
            {
                RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.ExInputSink, reciever.Handle);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to enable scroll function. {ex.Message}");
            }
        }
Exemple #12
0
        private void MainWindow_Shown(object sender, EventArgs e)
        {
            // Update title
            Version v = Assembly.GetExecutingAssembly().GetName().Version;

            this.Text = $"Raw Input Monitor V{v.Major}.{v.Minor}";

            // Get devices
            DeviceListUpdate();

            // Get our handle
            int     pid     = Process.GetCurrentProcess().Id;
            Process proc    = Process.GetProcessById(pid);
            var     wHandle = proc.MainWindowHandle;

            // Register to raw input events
            RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.InputSink, wHandle);
            RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.InputSink, wHandle);
        }
Exemple #13
0
        public static Thread JoystickListenerThread(OnDeviceEvent onDeviceEventCallback, string deviceIdFilter = null)
        {
            Thread joystickListenerThread = new Thread(() =>
            {
                var joystick = new RawInputReceiverWindow();
                RawInputData previousMessage = null;
                joystick.Input += (sender, e) =>
                {
                    if (deviceIdFilter != e.Data.Header.DeviceHandle.ToString())
                    {
                        return;
                    }
                    if (previousMessage?.ToString() == e.Data.ToString())
                    {
                        return;
                    }
                    dynamic dataObject = e.Data;
                    if (dataObject.Hid.Count > 1)
                    {
                        return;
                    }
                    previousMessage = e.Data;
                    onDeviceEventCallback(e.Data);
                };

                try
                {
                    // Register the HidUsageAndPage to watch any device.
                    RawInputDevice.RegisterDevice(HidUsageAndPage.Joystick, RawInputDeviceFlags.ExInputSink, joystick.Handle);
                    Application.Run();
                }
                finally
                {
                    RawInputDevice.UnregisterDevice(HidUsageAndPage.Joystick);
                }
            });

            joystickListenerThread.Priority = ThreadPriority.Highest;
            joystickListenerThread.Start();
            return(joystickListenerThread);
        }
Exemple #14
0
        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Setup INI file and create it if nessesary.
            string iniFilePath = $"{Application.StartupPath}\\config.ini";

            if (File.Exists(iniFilePath) == false)
            {
                File.Create(iniFilePath).Close();
            }
            INIFile = new INIFile(iniFilePath);

            InputWindow = new RawInputWindow();
            // RawInputDevice.RegisterDevice(HidUsageAndPage.TouchPad, RawInputDeviceFlags.ExInputSink, InputWindow.Handle);
            RawInputDevice.RegisterDevice(HidUsageAndPage.Joystick, RawInputDeviceFlags.ExInputSink, InputWindow.Handle);

            MainWindow = new MainWindow();
            Application.Run(MainWindow);

            RawInputDevice.UnregisterDevice(HidUsageAndPage.GamePad);
        }
Exemple #15
0
        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}");
            }

            // 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);

                Application.Run();
            }
            finally
            {
                RawInputDevice.UnregisterDevice(HidUsageAndPage.Keyboard);
            }
        }
Exemple #16
0
        private void Conn_Click(object sender, EventArgs e)
        {
            //[2400, 9600, 19200, 38400, 57600, 115200, 250000, 500000, 1000000]
            port             = new SerialPort(port_name, 19200, Parity.None, 8, StopBits.One);
            port.ReadTimeout = 2000;
            try
            {
                if (!(port.IsOpen))
                {
                    port.Open();
                }
                port.Write("\r\n");

                port.WriteLine("M115");
                //port.WriteLine("G1 F250");
                //Enable Event Handler
                port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            }
            catch (Exception ex)
            {
                messageBx.Text += "Error opening/writing to serial port :: " + ex.Message + "Error!";
            }
            RawInputDevice.RegisterDevice(HidUsageAndPage.Joystick, RawInputDeviceFlags.ExInputSink, window1.Handle);
        }
Exemple #17
0
        public static Thread KeyboardListenerThread(OnDeviceEvent onDeviceEventCallback, string deviceIdFilter = null)
        {
            Thread keyboardListenerThread = new Thread(() =>
            {
                var keyboard = new RawInputReceiverWindow();
                RawInputData previousMessage = null;
                keyboard.Input += (sender, e) =>
                {
                    if (deviceIdFilter != e.Data.Header.DeviceHandle.ToString())
                    {
                        return;
                    }
                    if (previousMessage?.ToString() == e.Data.ToString())
                    {
                        return;
                    }
                    previousMessage = e.Data;
                    onDeviceEventCallback(e.Data);
                };

                try
                {
                    // Register the HidUsageAndPage to watch any device.
                    RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.ExInputSink, keyboard.Handle);
                    Application.Run();
                }
                finally
                {
                    RawInputDevice.UnregisterDevice(HidUsageAndPage.Keyboard);
                }
            });

            keyboardListenerThread.Priority = ThreadPriority.Highest;
            keyboardListenerThread.Start();
            return(keyboardListenerThread);
        }
Exemple #18
0
        static async Task Main(string[] args)
        {
            // To begin catching inputs, first make a window that listens WM_INPUT.
            var window = new RawInputReceiverWindow();

            // Build the IPC Pipe
            var Client = new CommonCommunication.Client();

            // Create the event handler
            window.Input += async(sender, e) =>
            {
                // ECVILLA Device
                if (e.Data.Device.DevicePath == @"\\?\HID#VID_0C45&PID_760A&MI_00#b&22a65cf9&0&0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}")
                {
                    if (false == Client.IsConnected())
                    {
                        // Connect to IPC service
                        Console.WriteLine($"Connecting to elite_keyboard");

                        await Client.CreateConnection("elite_keyboard").ConfigureAwait(false);

                        Console.WriteLine($"Connected to elite_keyboard");
                    }

                    if (e.Data is RawInputKeyboardData)
                    {
                        var keyboardData = e.Data as RawInputKeyboardData;

                        var messageBody = new EliteJoystick.Common.Messages.KeyboardMessage
                        {
                            VirutalKey = keyboardData.Keyboard.VirutalKey,
                            ScanCode   = keyboardData.Keyboard.ScanCode,
                            Flags      = (int)keyboardData.Keyboard.Flags
                        };

                        var message = new CommonCommunication.Message
                        {
                            Type = "keypress",
                            Data = JsonConvert.SerializeObject(messageBody)
                        };

                        // Send the message to the IPC channel
                        await Client.SendMessageAsync(JsonConvert.SerializeObject(message)).ConfigureAwait(false);

                        Console.WriteLine($"{e.Data.Device.DevicePath}: {e.Data}");
                    }
                }
            };

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

                Console.WriteLine($"Ready");

                // Run the listener
                Application.Run();
            }
            finally
            {
                RawInputDevice.UnregisterDevice(HidUsageAndPage.Keyboard);
            }
        }