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); } }
internal override bool Initialize() { if (!base.Initialize()) { return(false); } try { RawInputDevice r = new RawInputDevice(); r.UsagePage = HIDUsagePage.Generic; r.Usage = HIDUsage.Mouse; r.Flags = RawInputDeviceFlags.None; r.WindowHandle = windowHandle; if (!Native.RegisterRawInputDevices(new[] { r }, 1, sizeof(RawInputDevice))) { return(false); } } catch { } OnMouse += MouseHandler; return(true); }
public override void Init() { this.LogLine("KeyServiceRawInput.Init()"); var rawInputDevice = new RawInputDevice { UsagePage = HIDUsagePage.Generic, Usage = HIDUsage.Keyboard, Flags = RIDEV.INPUTSINK | RIDEV.DEVNOTIFY, WindowHandle = RunService.Handle, }; var result = Win32.RegisterRawInputDevices ( new RawInputDevice[] { rawInputDevice }, 1, Marshal.SizeOf(typeof(RawInputDevice)) ); if (!result) { var error = Win32.GetLastError(); this.LogLine(" => Error : {0}", error.ToRepr()); } else { this.LogLine(" => Success"); } RunService.RegisterMessageProcessor(this); }
public static List <DeviceModel> GetAllDevices() { List <DeviceModel> devices = new List <DeviceModel>(); var result = RawInputDevice.GetDevices(); foreach (var item in result) { var device = new DeviceModel(); device.IsSelected = false; try { device.Name = $"{item.ProductName}({item.ManufacturerName})"; } catch { continue; } device.Type = item.GetCustomDeviceType(); device.Id = item.Handle.ToString(); devices.Add(device); } //devices = devices.GroupBy(x => x.Id).Select(x => x.First()).ToList(); return(devices); }
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); }
public override void Uninit() { this.LogLine("KeyServiceRawInput.Uninit()"); foreach (var registeredShortcut in RegisteredShortcuts.Values.ToList()) { UnregisterShortcut(registeredShortcut); } RegisteredShortcuts.Clear(); var rawInputDevice = new RawInputDevice { UsagePage = HIDUsagePage.Generic, Usage = HIDUsage.Keyboard, Flags = RIDEV.REMOVE, WindowHandle = IntPtr.Zero, }; var result = Win32.RegisterRawInputDevices ( new RawInputDevice[] { rawInputDevice }, 1, Marshal.SizeOf(typeof(RawInputDevice)) ); RunService.UnregisterMessageProcessor(this); }
internal override bool Initialize() { bool success = false; try { RawInputDevice r = new RawInputDevice(); WindowsGameWindow w = GameBase.Instance.Window as WindowsGameWindow; r.UsagePage = HIDUsagePage.Generic; r.Usage = HIDUsage.Keyboard; r.Flags = RawInputDeviceFlags.InputSink; r.WindowHandle = w.Handle; success = Native.RegisterRawInputDevices(new[] { r }, 1, sizeof(RawInputDevice)); if (!success) { ConfigManager.sRawInput = false; return(false); } } catch { } success = base.Initialize(); if (success) { OnKeyboard += handler; } return(success); }
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 Form1() { WindowState = FormWindowState.Minimized; ShowInTaskbar = false; InitializeComponent(); AllocConsole(); sz = 8192; ri = (RawInput *)Marshal.AllocHGlobal(8192); var regs = new RawInputDevice[] { new RawInputDevice { UsagePage = HIDUsagePage.Generic, Usage = HIDUsage.Mouse, Flags = RawInputDeviceFlags.InputSink | RawInputDeviceFlags.NoLegacy, WindowHandle = this.Handle } }; RegisterRawInputDevices( regs, regs.Length, Marshal.SizeOf(typeof(RawInputDevice)) ); }
private string GetFancyDeviceName(RawInputDevice device) { string fancyName = ""; if (device == null) return "Unknown Device"; if (device.DevicePath != null) { // Aimtrak if (device.VendorId == 0xD209 && device.ProductId >= 0x1601 && device.ProductId <= 0x1608) { fancyName = String.Format("Ultimarc AimTrak #{0}", device.ProductId - 0x1600); } // Sinden else if (device.VendorId == 0x16C0) { if (device.ProductId == 0x0F01) fancyName = "Sinden Lightgun Blue"; else if (device.ProductId == 0x0F02) fancyName = "Sinden Lightgun Red"; else if (device.ProductId == 0x0F38) fancyName = "Sinden Lightgun Black"; else if (device.ProductId == 0x0F39) fancyName = "Sinden Lightgun Player 2"; } // DolphinBar else if (device.VendorId == 0x0079 && device.ProductId == 0x1802) { fancyName = "Mayflash DolphinBar " + device.DevicePath.Split('#')[2].Split('&')[1].ToUpper(); // CRC part of path should be unique } } // Other if (fancyName == "") { string manufacturer = device.ManufacturerName?.Trim() ?? ""; if(manufacturer == "") manufacturer = "(Unknown manufacturer)"; string productName = device.ProductName?.Trim() ?? ""; if(productName == "") productName = "(Unknown product)"; if(manufacturer == "(Standard keyboards)" || productName.Contains(manufacturer)) { // omit the manufacturer name fancyName = productName; } else { // combined manufacturer / product name fancyName = String.Format("{0} {1}", manufacturer, productName); } } return fancyName; }
private string GetFancyDeviceName(RawInputDevice device) { string fancyName = ""; if (device == null) { return("Unknown device"); } if (device.DevicePath != null) { // Aimtrak if (device.VendorId == 0xD209 && device.ProductId >= 0x1601 && device.ProductId <= 0x1608) { fancyName = String.Format("Ultimarc AimTrak #{0}", device.ProductId - 0x1600); } // Sinden else if (device.VendorId == 0x16C0) { if (device.ProductId == 0x0F01) { fancyName = "Sinden Lightgun Blue"; } else if (device.ProductId == 0x0F02) { fancyName = "Sinden Lightgun Red"; } else if (device.ProductId == 0x0F38) { fancyName = "Sinden Lightgun Black"; } else if (device.ProductId == 0x0F39) { fancyName = "Sinden Lightgun Player 2"; } } // DolphinBar else if (device.VendorId == 0x0079 && device.ProductId == 0x1802) { fancyName = "Mayflash DolphinBar"; } } // Other if (fancyName == "") { string manufacturer = device.ManufacturerName.Trim(); if (manufacturer == "(Standard keyboards)" || device.ProductName.Contains(manufacturer)) { manufacturer = ""; } fancyName = String.Format("{0} {1}", manufacturer, device.ProductName.Trim()).Trim(); } return(fancyName); }
//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; }
/// <summary> /// Starts catching input messages from keyboards. /// </summary> /// <param name="handle">The handle of the receiver (form) which will process the caught messages.</param> /// <param name="captureWhileActiveOnly">Whether the catching should be taken while the receiver window is active in foreground only.</param> public static void StartCatching(IntPtr handle, bool captureWhileActiveOnly) { var devices = new RawInputDevice[] { new RawInputDevice(handle, captureWhileActiveOnly) }; if (!RegisterRawInputDevices(devices, 1, rawInputDeviceElementSize)) { throw new ApplicationException("Failed to register raw input device."); } }
protected virtual void Dispose(bool disposing) { _source?.RemoveHook(MessageSink); RawInputDevice.UnregisterDevice(HidUsageAndPage.Keyboard); RawInputDevice.UnregisterDevice(HidUsageAndPage.Mouse); _source = null; }
private void OnDisable() { RawInputWindowProcedure.Instance.ReceiveRawInput -= OnReceiveRawInput; #if UNITY_EDITOR Debug.Log("RawInputDevice.UnregisterDevice was skipped in editor"); #else RawInputDevice.UnregisterDevice(HidUsageAndPage.Mouse); #endif }
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); }
public MainForm() { AppDomain.CurrentDomain.ProcessExit += Exited; sz = 8192; ri = (RawInput *)Marshal.AllocHGlobal(8192); fs = new FileStream( "inputrec.dat.gz", System.IO.FileMode.Append, System.IO.FileAccess.Write ); gs = new GZipStream(fs, CompressionLevel.Optimal); InitializeComponent(); AllocConsole(); // Low-level hooks do not require an injectable DLL. // Using WH_KEYBOARD allows detection of per-application // keyboard translation information; no benefit is known // for WH_MOUSE. SetWindowsHookEx( WindowsHookType.WH_MOUSE_LL, LowLevelMouseProc, IntPtr.Zero, 0 ); var regs = new RawInputDevice[] { // TODO: Not getting scroll events on other windows? // Not getting *trackpad* scroll events. new RawInputDevice { UsagePage = HIDUsagePage.Generic, Usage = HIDUsage.Mouse, Flags = RawInputDeviceFlags.InputSink | RawInputDeviceFlags.NoLegacy, WindowHandle = this.Handle }, new RawInputDevice { UsagePage = HIDUsagePage.Generic, Usage = HIDUsage.Gamepad, Flags = RawInputDeviceFlags.InputSink, WindowHandle = this.Handle }, new RawInputDevice { UsagePage = HIDUsagePage.Digitizer, Usage = HIDUsage.Joystick, Flags = RawInputDeviceFlags.InputSink, WindowHandle = this.Handle } }; RegisterRawInputDevices( regs, regs.Length, Marshal.SizeOf(typeof(RawInputDevice)) ); }
public List<string> GetMouseDeviceList() { var mice = RawInputDevice.GetDevices().OfType<RawInputMouse>(); List<string> deviceList = new List<string>(); foreach (var device in mice) deviceList.Add(GetFancyDeviceName(device)); return deviceList; }
private static unsafe bool RegisterDevice(RawInputDevice device) { var devices = new RawInputDevice[1] { device }; fixed(void *ptr = devices) { return(Win32.RegisterRawInputDevices(ptr, 1, (uint)sizeof(RawInputDevice))); } }
public static bool RegisterDevice(UsagePage usagePage, UsageId usageId, ModeFlags flags, IntPtr target) { var device = new RawInputDevice { UsagePage = (ushort)usagePage, Usage = (ushort)usageId, Flags = (uint)flags, Target = target }; return(RegisterDevice(device)); }
public RawInputDevice GetKeyboardDeviceByBindName(string bindName) { var keyboards = RawInputDevice.GetDevices().OfType<RawInputKeyboard>(); foreach (var device in keyboards) { if (bindName.StartsWith(GetFancyDeviceName(device))) return device; } return null; }
public RawInputDevice GetMouseDeviceByBindName(string bindName) { var mice = RawInputDevice.GetDevices().OfType<RawInputMouse>(); foreach (var device in mice) { if (bindName.StartsWith(GetFancyDeviceName(device))) return device; } return null; }
public RawInputDevice GetMouseDeviceByName(string deviceName) { var mice = RawInputDevice.GetDevices().OfType<RawInputMouse>(); foreach (var device in mice) { if (GetFancyDeviceName(device) == deviceName) return device; } return null; }
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 DeviceListAdd(RawInputDevice device) { string vid = "0000"; string pid = "0000"; if (device.DevicePath != null) { vid = device.VendorId.ToString("X4"); pid = device.ProductId.ToString("X4"); } string[] row = { RawInputDeviceHandle.GetRawValue(device.Handle).ToString("X8"), device.DeviceType.ToString(), vid, pid, device.ProductName, device.ManufacturerName, "?", "?", "?", (screenWidth / 2).ToString(), (screenHeight / 2).ToString(), GetFancyDeviceName(device), device.DevicePath }; table.Rows.Add(row); }
public GlobalMouseHook(IntPtr hwnd) { var rid = new RawInputDevice[1]; rid[0].UsagePage = HidUsagePage.GENERIC; rid[0].Usage = HidUsage.Mouse; rid[0].Flags = RawInputDeviceFlags.INPUTSINK; rid[0].Target = hwnd; if (!RegisterRawInputDevices(rid, (uint)rid.Length, (uint)Marshal.SizeOf(rid[0]))) { throw new ApplicationException("Failed to register raw input device(s)."); } }
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; }
private void Main_FormClosing(object sender, FormClosingEventArgs e) { RawInputDevice.UnregisterDevice(HidUsageAndPage.Joystick); //RawInputDevice.UnregisterDevice(HidUsageAndPage.GamePad); if (port != null) { if (port.IsOpen) { port.WriteLine("M106 S0"); port.WriteLine("M18"); port.Close(); } } }
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); }
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 static void RegisterInput(IntPtr handle) { RawInputDevice[] rid = new RawInputDevice[2]; rid[0].UsagePage = HidUsagePage.GENERIC; // 0x01 rid[0].Usage = HidUsage.Mouse; // 0x02 rid[0].Flags = RawInputDeviceFlags.INPUTSINK; rid[0].Target = handle; rid[1].UsagePage = HidUsagePage.GENERIC; // 0x01 rid[1].Usage = HidUsage.Keyboard; // 0x06 rid[1].Flags = RawInputDeviceFlags.INPUTSINK; rid[1].Target = handle; RegisterRawInputDevices(rid, (uint)rid.Length, (uint)Marshal.SizeOf(rid[0])); }
/// <summary>Returns an array of <see cref="RawInputDevice"/> structures containing information about the raw input devices for the current application.</summary> /// <returns>Returns an array of <see cref="RawInputDevice"/> structures containing information about the raw input devices for the current application; the array can be empty, but not null.</returns> /// <exception cref="InvalidDataException"/> /// <exception cref="Win32Exception"/> internal static RawInputDevice[] GetRegisteredRawInputDevices() { var structSize = Marshal.SizeOf( typeof( RawInputDevice ) ); var deviceCount = 0; var result = GetRegisteredRawInputDevices( null, ref deviceCount, structSize ); if( result != 0 ) { if( result == -1 ) throw new Win32Exception( "Failed to retrieve registered raw input device count.", GetExceptionForLastWin32Error() ); throw new InvalidDataException( "Failed to retrieve registered raw input device count." ); } if( deviceCount < 0 ) throw new InvalidDataException( "Invalid registered raw input device count." ); var rawInputDevices = new RawInputDevice[ deviceCount ]; result = GetRegisteredRawInputDevices( rawInputDevices, ref deviceCount, structSize ); if( result == -1 ) throw new Win32Exception( "Failed to retrieve registered raw input devices.", GetExceptionForLastWin32Error() ); return rawInputDevices; }
/// <summary> /// Registers the devices that supply the raw input data. /// </summary> /// <param name="usagePage">The usage page.</param> /// <param name="usageId">The usage id.</param> /// <param name="flags">The flags.</param> /// <param name="target">The target.</param> /// <param name="options">The options.</param> public static void RegisterDevice(UsagePage usagePage, UsageId usageId, DeviceFlags flags, IntPtr target, RegisterDeviceOptions options = RegisterDeviceOptions.Default) { var rawInputDevices = new RawInputDevice[1]; rawInputDevices[0].UsagePage = (short)usagePage; rawInputDevices[0].Usage = (short)usageId; rawInputDevices[0].Flags = (int)flags; rawInputDevices[0].Target = target; // Register this device RawInputFunctions.RegisterRawInputDevices(rawInputDevices, 1, Utilities.SizeOf<RawInputDevice>()); if (options != RegisterDeviceOptions.NoFiltering && rawInputMessageFilter == null) { rawInputMessageFilter = new RawInputMessageFilter(); if (options == RegisterDeviceOptions.Default) { Application.AddMessageFilter(rawInputMessageFilter); } else { MessageFilterHook.AddMessageFilter(target, rawInputMessageFilter); } } }
static extern bool RegisterRawInputDevices(RawInputDevice[] pRawInputDevice, uint uiNumDevices, uint cbSize);
/// <summary> /// Registers the devices that supply the raw input data. /// </summary> /// <param name="usagePage">The usage page.</param> /// <param name="usageId">The usage id.</param> /// <param name="flags">The flags.</param> /// <param name="target">The target.</param> /// <param name="addMessageFilter">if set to <c>true</c> register message filter to Application.AddMessageFilter.</param> public static void RegisterDevice(UsagePage usagePage, UsageId usageId, DeviceFlags flags, IntPtr target, bool addMessageFilter = true) { var rawInputDevices = new RawInputDevice[1]; rawInputDevices[0].UsagePage = (short) usagePage; rawInputDevices[0].Usage = (short) usageId; rawInputDevices[0].Flags = (int) flags; rawInputDevices[0].Target = target; // Register this device RawInputFunctions.RegisterRawInputDevices(rawInputDevices, 1, Utilities.SizeOf<RawInputDevice>()); if (rawInputMessageFilter == null && addMessageFilter) { rawInputMessageFilter = new RawInputMessageFilter(); Application.AddMessageFilter(rawInputMessageFilter); } }
/// <summary>Causes the target window to receive raw input messages. /// <para>Important: that window must then override its WndProc method to call <see cref="WndProc"/> prior to its base method.</para> /// </summary> /// <param name="targetWindow">The target window.</param> /// <param name="options">One or more <see cref="RawInputDeviceRegistrationOptions"/>.</param> /// <param name="usages">At least one TLC usage.</param> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentException"/> public static void Register( IWin32Window targetWindow, RawInputDeviceRegistrationOptions options, params TopLevelCollectionUsage[] usages ) { if( usages == null ) throw new ArgumentNullException( "usages" ); if( usages.Length == 0 ) throw new ArgumentException( "No TLC specified.", "usages" ); var windowHandle = ( targetWindow == null ) ? IntPtr.Zero : targetWindow.Handle; var devices = new RawInputDevice[ usages.Length ]; for( var d = 0; d < usages.Length; d++ ) devices[ d ] = new RawInputDevice( usages[ d ], options, windowHandle ); NativeMethods.RegisterRawInputDevices( devices ); }
/// <summary> /// Registers the devices that supply the raw input data. /// </summary> /// <param name="usagePage">The usage page.</param> /// <param name="usageId">The usage id.</param> /// <param name="flags">The flags.</param> /// <param name="target">The target.</param> /// <param name="addMessageFilter">if set to <c>true</c> register message filter to Application.AddMessageFilter.</param> public static void RegisterDevice(UsagePage usagePage, UsageId usageId, DeviceFlags flags, IntPtr target, bool addMessageFilter = true) { if (target == IntPtr.Zero) { target = Win32Native.GetFocus(); } var rawInputDevices = new RawInputDevice[1]; rawInputDevices[0].UsagePage = (short) usagePage; rawInputDevices[0].Usage = (short) usageId; rawInputDevices[0].Flags = (int) flags; rawInputDevices[0].Target = target; // Register this device RawInputFunctions.RegisterRawInputDevices(rawInputDevices, 1, Utilities.SizeOf<RawInputDevice>()); if (rawInputMessageFilter == null && addMessageFilter) { rawInputMessageFilter = new RawInputMessageFilter(); MessageFilterHook.AddMessageFilter(target, rawInputMessageFilter); } }