/// <summary> /// Function will check if provide <see cref="SystemVolume"/> is accessible /// It has a meaning for removable devices such as CDRom /// </summary> /// <param name="device">The device to query</param> /// <returns><c>true</c> if device is accessible and could be queried, otherwise <c>false</c></returns> internal static bool IsAccessible(DeviceHandle device) { bool functionResult = false; int lpBytesReturned = 0; NativeOverlapped nativeOverlapped = new NativeOverlapped(); try { lock (lockMe) { IntPtr handle = device.OpenDeviceHandle(); functionResult = UnsafeNativeMethods.DeviceIoControl(handle, IoControlCode.IOCTL_STORAGE_CHECK_VERIFY, IntPtr.Zero, 0, IntPtr.Zero, 0, ref lpBytesReturned, ref nativeOverlapped); device.CloseDeviceHandle(); return(functionResult); } } catch (Exception exp_gen) { throw new Win32Exception("Exception occurred while trying to work with Windows kernel", exp_gen); } }
private bool disposedValue; // To detect redundant calls private void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _arrivalCancellationTokenSourcePrimary.Cancel(); _arrivalCancellationTokenSourceSecondary.Cancel(); _removalCancellationTokenSourcePrimary.Cancel(); _removalCancellationTokenSourceSecondary.Cancel(); foreach (var child in Children) { child.Dispose(); } Children.Clear(); } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. int bytesReturned; DeviceHandle.OverlappedDeviceIoControl( IoctlAirbenderHostShutdown, IntPtr.Zero, 0, IntPtr.Zero, 0, out bytesReturned); DeviceHandle?.Close(); disposedValue = true; } }
internal T GetDataForDevice(DeviceHandle device, IoControlCode controlCode) { bool functionResult = false; IntPtr ptrInputData = IntPtr.Zero; var structureSize = Marshal.SizeOf(typeof(T)); int lpBytesReturned = 0; NativeOverlapped nativeOverlapped = new NativeOverlapped(); int win32Error = 0; try { // First try ptrInputData = Marshal.AllocHGlobal(structureSize); while (functionResult == false) { lock (lockMe) { IntPtr handle = device.OpenDeviceHandle(); functionResult = UnsafeNativeMethods.DeviceIoControl(handle, controlCode, IntPtr.Zero, 0, ptrInputData, structureSize, ref lpBytesReturned, ref nativeOverlapped); win32Error = Marshal.GetLastWin32Error(); device.CloseDeviceHandle(); } if (functionResult == false) { if (win32Error == UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) { Marshal.FreeHGlobal(ptrInputData); checked { structureSize = structureSize * 2; } ptrInputData = Marshal.AllocHGlobal(structureSize); } else { throw new Win32Exception("Could not acquire information from windows kernel.", new Win32Exception(win32Error)); } } } T data = (T)Marshal.PtrToStructure(ptrInputData, typeof(T)); return(data); } catch (Exception exp_gen) { throw new Win32Exception("Exception occurred while trying to work with Windows kernel", exp_gen); } finally { Marshal.FreeHGlobal(ptrInputData); } }
/// <inheritdoc /> public override void PairTo(PhysicalAddress host) { var length = Marshal.SizeOf(typeof(FireshockSetHostBdAddr)); var pData = Marshal.AllocHGlobal(length); Marshal.Copy(host.GetAddressBytes(), 0, pData, length); try { var ret = DeviceHandle.OverlappedDeviceIoControl( IoctlFireshockSetHostBdAddr, pData, length, IntPtr.Zero, 0, out _); if (!ret) { throw new FireShockSetHostBdAddrFailedException( $"Failed to pair {ClientAddress} to {host}", new Win32Exception(Marshal.GetLastWin32Error())); } HostAddress = host; } finally { Marshal.FreeHGlobal(pData); } }
public void SendShutDown() { DeviceHandle handle = GetHandle(DEV1); // Check the state of the device if (handle != DeviceHandle.INVALID) { // Save the device status to the record field RetrieveDeviceRecord(handle); // If not suspended, shut down if (record.GetStatus() != DEVICE_SUSPENDED) { PauseDevice(handle); ClearDeviceWorkQueue(handle); CloseDevice(handle); } else { Logger.Log("Device suspended. Unable to shut down"); } } else { Logger.Log("Invalid handle for: " + DEV1); } }
protected override void RequestInputReportWorker(object cancellationToken) { var token = (CancellationToken)cancellationToken; var buffer = new byte[0x32]; var unmanagedBuffer = Marshal.AllocHGlobal(buffer.Length); try { while (!token.IsCancellationRequested) { var ret = DeviceHandle.OverlappedDeviceIoControl( IOCTL_BTHPS3_HID_INTERRUPT_READ, IntPtr.Zero, 0, unmanagedBuffer, buffer.Length, out _ ); if (!ret) { OnDisconnected(); return; } Marshal.Copy(unmanagedBuffer, buffer, 0, buffer.Length); /* * When connected via Bluetooth the Sixaxis occasionally sends * a report with the second byte 0xff and the rest zeroed. * * This report does not reflect the actual state of the * controller must be ignored to avoid generating false input * events. */ if (buffer[2] == 0xff) { continue; } try { OnInputReport(DualShock3InputReport.FromBuffer(buffer.Skip(1).ToArray())); } catch (InvalidDataException ide) { Log.Warning("Malformed input report received: {Exception}", ide); } } } catch (Exception ex) { Log.Error("{Exception}", ex); } finally { Marshal.FreeHGlobal(unmanagedBuffer); } }
public MusicDevice(IMusicPluginObject musicPlugin, string name, MusicType mt) { _musicDriverName = musicPlugin.Name; _musicDriverId = musicPlugin.Id; _name = name; _type = mt; Handle = new DeviceHandle(CompleteId.GetHashCode()); }
/// <summary> /// Frees all available resources. /// </summary> public void Dispose() { if (handle != null) { handle.Dispose(); handle = null; } }
/// <inheritdoc /> public override string ToString() { if (_productLoaded) { return(_product); } return(DeviceHandle.ToString()); }
/// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// /// <param name="disposing"><c>true</c> to release both managed /// and unmanaged resources; <c>false</c> to release only unmanaged /// resources.</param> /// protected virtual void Dispose(bool disposing) { if (disposing) { // free managed resources mask.Dispose(); mask = null; } }
private FireShockDevice(string path, Kernel32.SafeObjectHandle handle, int index) : base( DualShockConnectionType.USB, handle, index) { DevicePath = path; var length = Marshal.SizeOf(typeof(FireshockGetDeviceBdAddr)); var pData = Marshal.AllocHGlobal(length); try { var ret = DeviceHandle.OverlappedDeviceIoControl( IoctlFireshockGetDeviceBdAddr, IntPtr.Zero, 0, pData, length, out _); if (!ret) { throw new FireShockGetDeviceBdAddrFailedException( $"Failed to request address of device {path}", new Win32Exception(Marshal.GetLastWin32Error())); } var resp = Marshal.PtrToStructure <FireshockGetDeviceBdAddr>(pData); ClientAddress = new PhysicalAddress(resp.Device.Address); } finally { Marshal.FreeHGlobal(pData); } length = Marshal.SizeOf(typeof(FireshockGetHostBdAddr)); pData = Marshal.AllocHGlobal(length); try { var ret = DeviceHandle.OverlappedDeviceIoControl( IoctlFireshockGetHostBdAddr, IntPtr.Zero, 0, pData, length, out _); if (!ret) { throw new FireShockGetHostBdAddrFailedException( $"Failed to request host address for device {ClientAddress}", new Win32Exception(Marshal.GetLastWin32Error())); } var resp = Marshal.PtrToStructure <FireshockGetHostBdAddr>(pData); HostAddress = new PhysicalAddress(resp.Host.Address); } finally { Marshal.FreeHGlobal(pData); } }
private void ChildDeviceArrivalWorker(object cancellationToken) { var token = (CancellationToken)cancellationToken; var requestSize = Marshal.SizeOf <AirbenderGetClientArrival>(); var requestBuffer = Marshal.AllocHGlobal(requestSize); try { while (!token.IsCancellationRequested) { // // This call blocks until the driver supplies new data. // var ret = DeviceHandle.OverlappedDeviceIoControl( IoctlAirbenderGetClientArrival, IntPtr.Zero, 0, requestBuffer, requestSize, out _); if (!ret) { throw new AirbenderGetClientArrivalFailedException( "Failed to receive device arrival event.", new Win32Exception(Marshal.GetLastWin32Error())); } var resp = Marshal.PtrToStructure <AirbenderGetClientArrival>(requestBuffer); switch (resp.DeviceType) { case DualShockDeviceType.DualShock3: var device = new AirBenderDualShock3( this, new PhysicalAddress(resp.ClientAddress.Address.Reverse().ToArray()), Children.Count); device.InputReportReceived += (sender, args) => InputReportReceived?.Invoke(this, new InputReportReceivedEventArgs((IDualShockDevice)sender, args.Report)); Children.Add(device); break; case DualShockDeviceType.DualShock4: throw new NotImplementedException(); default: throw new NotImplementedException(); } } } finally { Marshal.FreeHGlobal(requestBuffer); } }
public override int GetHashCode() { unchecked { var hashCode = (ProviderName != null ? ProviderName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (DeviceHandle != null ? DeviceHandle.GetHashCode() : 0); hashCode = (hashCode * 397) ^ DeviceNumber; return(hashCode); } }
/// <summary> /// Resets the enumeration. /// </summary> public void Reset() { Dispose(); handle = new DeviceHandle(sess, sess.CeFindFirstDatabase(dbType)); if (handle.IsInvalid) { throw new RapiException(sess.CeGetLastError()); } current = null; }
private void TryToShutDown() { DeviceHandle handle = GetHandle(DEV1); RetrieveDeviceRecord(handle); PauseDevice(handle); ClearDeviceWorkQueue(handle); CloseDevice(handle); }
public static Error TransferAsync( DeviceHandle device, byte endPoint, EndpointType endPointType, IntPtr buffer, int offset, int length, int timeout, out int transferLength) { return(TransferAsync(device, endPoint, endPointType, buffer, offset, length, timeout, 0, out transferLength)); }
/// <summary> /// Initializes a new instance of the <see cref="CaptureCursor"/> class. /// </summary> /// public CaptureCursor() { // By preallocating those we will prevent extra // object allocations in middle of processing. IntPtr desk = NativeMethods.GetDesktopWindow(); using (Graphics desktop = Graphics.FromHwnd(desk)) mask = SafeNativeMethods.CreateCompatibleDC(desktop); cursorInfoSize = Marshal.SizeOf(typeof(CursorInfo)); }
/// <summary> /// Closes the device. /// </summary> public void Close() { this.EnsureNotDisposed(); if (!this.IsOpen) { return; } this.deviceHandle.Dispose(); this.deviceHandle = null; }
protected override void RequestInputReportWorker(object cancellationToken) { var token = (CancellationToken)cancellationToken; var buffer = new byte[512]; var unmanagedBuffer = Marshal.AllocHGlobal(buffer.Length); try { while (!token.IsCancellationRequested) { var ret = DeviceHandle.OverlappedReadFile( unmanagedBuffer, buffer.Length, out var bytesReturned); if (!ret) { var nex = new Win32Exception(Marshal.GetLastWin32Error()); // Valid exception in case the device got surprise-removed, end worker if (nex.NativeErrorCode == Win32ErrorCode.ERROR_OPERATION_ABORTED) { return; } throw new FireShockReadInputReportFailedException( "Failed to read input report.", nex); } Marshal.Copy(unmanagedBuffer, buffer, 0, bytesReturned); try { OnInputReport(DualShock3InputReport.FromBuffer(buffer)); } catch (InvalidDataException ide) { Log.Warning("Malformed input report received: {Exception}", ide); } } } catch (Exception ex) { Log.Error("{Exception}", ex); } finally { Marshal.FreeHGlobal(unmanagedBuffer); } }
NativeInputDevice FindAttachedDevice(DeviceHandle deviceHandle) { int attachedDevicesCount = attachedDevices.Count; for (int i = 0; i < attachedDevicesCount; i++) { var device = attachedDevices[i]; if (device.Handle == deviceHandle) { return(device); } } return(null); }
/// <summary> /// Periodically submits output report state changes of this controller. /// </summary> /// <param name="l">The interval.</param> protected override void OnOutputReport(long l) { Marshal.Copy(HidOutputReport, 0, OutputReportBuffer, HidOutputReport.Length); var ret = DeviceHandle.OverlappedWriteFile( OutputReportBuffer, HidOutputReport.Length, out _); if (!ret) { OnDisconnected(); } }
/// <summary> /// Opens a device, allowing you to perform I/O on this device. /// </summary> public void Open() { this.EnsureNotDisposed(); if (this.IsOpen) { return; } IntPtr deviceHandle = IntPtr.Zero; NativeMethods.Open(this.device, ref deviceHandle).ThrowOnError(); this.deviceHandle = DeviceHandle.DangerousCreate(deviceHandle); this.descriptor = null; }
protected void SendHidCommand(IntPtr buffer, int bufferLength) { var ret = DeviceHandle.OverlappedDeviceIoControl( IOCTL_BTHPS3_HID_CONTROL_WRITE, buffer, bufferLength, IntPtr.Zero, 0, out _ ); if (!ret) { OnDisconnected(); } }
void DetectDevice(DeviceHandle deviceHandle, NativeDeviceInfo deviceInfo) { // Try to find a matching profile for this device. NativeInputDeviceProfile deviceProfile = null; deviceProfile = deviceProfile ?? customDeviceProfiles.Find(profile => profile.Matches(deviceInfo)); deviceProfile = deviceProfile ?? systemDeviceProfiles.Find(profile => profile.Matches(deviceInfo)); deviceProfile = deviceProfile ?? customDeviceProfiles.Find(profile => profile.LastResortMatches(deviceInfo)); deviceProfile = deviceProfile ?? systemDeviceProfiles.Find(profile => profile.LastResortMatches(deviceInfo)); // Find a matching previously attached device or create a new one. var device = FindDetachedDevice(deviceInfo) ?? new NativeInputDevice(); device.Initialize(deviceHandle, deviceInfo, deviceProfile); AttachDevice(device); }
protected override void RequestInputReportWorker(object cancellationToken) { var token = (CancellationToken)cancellationToken; var buffer = new byte[0x32]; var unmanagedBuffer = Marshal.AllocHGlobal(buffer.Length); try { while (!token.IsCancellationRequested) { var ret = DeviceHandle.OverlappedDeviceIoControl( IOCTL_BTHPS3_HID_INTERRUPT_READ, IntPtr.Zero, 0, unmanagedBuffer, buffer.Length, out _ ); if (!ret) { OnDisconnected(); return; } Marshal.Copy(unmanagedBuffer, buffer, 0, buffer.Length); try { OnInputReport(DualShock3InputReport.FromBuffer(buffer.Skip(1).ToArray())); } catch (InvalidDataException ide) { Log.Warning("Malformed input report received: {Exception}", ide); } } } catch (Exception ex) { Log.Error("{Exception}", ex); } finally { Marshal.FreeHGlobal(unmanagedBuffer); } }
protected override void Dispose(bool disposing) { // // Stop communication workers // base.Dispose(disposing); _outputReportConsumerTask?.Dispose(); if (DeviceHandle.IsClosed || DeviceHandle.IsInvalid) { return; } // // Request radio to disconnect remote device // var bthAddr = Convert.ToUInt64(ClientAddress.ToString(), 16); var bthAddrBuffer = BitConverter.GetBytes(bthAddr); var unmanagedBuffer = Marshal.AllocHGlobal(bthAddrBuffer.Length); Marshal.Copy(bthAddrBuffer, 0, unmanagedBuffer, bthAddrBuffer.Length); try { var ret = DeviceHandle.OverlappedDeviceIoControl( IOCTL_BTH_DISCONNECT_DEVICE, unmanagedBuffer, bthAddrBuffer.Length, IntPtr.Zero, 0, out _ ); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { Marshal.FreeHGlobal(unmanagedBuffer); } DeviceHandle.Dispose(); }
private void ChildDeviceRemovalWorker(object cancellationToken) { var token = (CancellationToken)cancellationToken; var requestSize = Marshal.SizeOf <AirbenderGetClientRemoval>(); var requestBuffer = Marshal.AllocHGlobal(requestSize); try { while (!token.IsCancellationRequested) { // // This call blocks until the driver supplies new data. // var ret = DeviceHandle.OverlappedDeviceIoControl( IoctlAirbenderGetClientRemoval, IntPtr.Zero, 0, requestBuffer, requestSize, out _); if (!ret) { throw new AirBenderGetClientRemovalFailedException( "Failed to receive device removal event.", new Win32Exception(Marshal.GetLastWin32Error())); } var resp = Marshal.PtrToStructure <AirbenderGetClientRemoval>(requestBuffer); var child = Children.First(c => c.ClientAddress.Equals(new PhysicalAddress(resp.ClientAddress.Address.Reverse().ToArray()))); child.Dispose(); Children.Remove(child); } } catch (Exception ex) { Log.Error("{Exception}", ex); } finally { Marshal.FreeHGlobal(requestBuffer); } }
private Error OpenNative() { this.EnsureNotDisposed(); if (this.IsOpen) { return(Error.Success); } IntPtr deviceHandle = IntPtr.Zero; var ret = NativeMethods.Open(this.device, ref deviceHandle); if (ret == Error.Success) { this.deviceHandle = DeviceHandle.DangerousCreate(deviceHandle); this.descriptor = null; } return(ret); }
/// <inheritdoc/> public bool TryOpen() { this.EnsureNotDisposed(); if (this.IsOpen) { return(true); } IntPtr deviceHandle = IntPtr.Zero; if (NativeMethods.Open(this.device, ref deviceHandle) == Error.Success) { this.deviceHandle = DeviceHandle.DangerousCreate(deviceHandle); return(true); } else { return(false); } }
private void OnKeyPressed(object sender, RawInputEventArg e) { if (CaptureHandleId) { DeviceHandle = Convert.ToInt32(e.KeyPressEvent.DeviceName); CaptureHandleId = false; lblNotification.ForeColor = System.Drawing.Color.Green; lblNotification.Text = "Device Registered Successfully"; } if (Track) { if (e.KeyPressEvent.DeviceName == DeviceHandle.ToString()) { X += e.KeyPressEvent.LastX / cpi / 0.022f; Y += e.KeyPressEvent.LastY / cpi / 0.022f; lblTotal.Text = Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2)).ToString();; lblX.Text = X.ToString(); lblY.Text = Y.ToString(); } } }
/// <summary> /// /// </summary> /// <param name="wait">The amount of time the background thread waits, before it adds the new dummy device</param> /// <param name="block"></param> public void SimulateAddOneDevice(TimeSpan wait, bool block = true) { Join(); _worker = new Thread(() => { Thread.Sleep(wait); var hmd = CreateHMD(); var handle = new DeviceHandle<IHMDDevice, IHMDInfo>(hmd); var msg = new MessageDeviceStatus { Device = this, DeviceHandle = handle, Type = MessageType.DeviceAdded }; _handler.OnMessage(msg); }); _worker.Start(); if (block) Join(); }
public bool CheckDevice(DeviceHandle handle) { return true; }
public NScumm.Core.Audio.Midi.IMidiDriver CreateInstance(IMixer mixer, DeviceHandle handle) { return new MidiDriver_TOWNS(mixer); }
public static extern uint hdInitDevice(DeviceHandle device);
public override IMidiDriver CreateInstance(IMixer mixer, DeviceHandle handle) { return new PCSpeakerDriver(mixer); }
private void DeviceAddAndRemove(TimeSpan amount) { var sw = new Stopwatch(); sw.Start(); while (!_exit && sw.Elapsed < amount) { // // Let's add the device // var hmd = CreateHMD(); var handle = new DeviceHandle<IHMDDevice, IHMDInfo>(hmd); var msg = new MessageDeviceStatus { Device = this, DeviceHandle = handle, Type = MessageType.DeviceAdded }; _handler.OnMessage(msg); // // And remove it again // msg = new MessageDeviceStatus { Device = this, DeviceHandle = handle, Type = MessageType.DeviceRemoved }; _handler.OnMessage(msg); } }
public override IMidiDriver CreateInstance(IMixer mixer, DeviceHandle handle) { return new NullMidiDriver(); }
public override IMidiDriver CreateInstance(IMixer mixer, DeviceHandle handle) { // TODO: return new AdlibMidiDriver(mixer); }