Adding HID consumer control event.
3 using System.Collections.Generic;
6 using System.Threading.Tasks;
7 using System.Diagnostics;
8 using System.Runtime.InteropServices;
9 using System.Windows.Forms;
10 using Microsoft.Win32.SafeHandles;
11 using System.ComponentModel;
13 using Hid = SharpLib.Hid;
16 namespace SharpDisplayManager
19 /// Implement handling of HID input reports notably to be able to launch an application using the Green Start button from IR remotes.
21 [System.ComponentModel.DesignerCategory("Code")]
22 public class FormMainHid : Form
24 [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "SwitchToThisWindow")]
25 public static extern void SwitchToThisWindow([System.Runtime.InteropServices.InAttribute()] System.IntPtr hwnd, [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)] bool fUnknown);
27 public delegate void OnHidEventDelegate(object aSender, Hid.Event aHidEvent);
30 /// Use notably to handle green start key from IR remote control
32 private Hid.Handler iHidHandler;
35 /// Register HID devices so that we receive corresponding WM_INPUT messages.
37 protected void RegisterHidDevices()
39 // Register the input device to receive the commands from the
40 // remote device. See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwmt/html/remote_control.asp
41 // for the vendor defined usage page.
43 RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[5];
46 rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.WindowsMediaCenterRemoteControl;
47 rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.WindowsMediaCenter.WindowsMediaCenterRemoteControl;
48 rid[i].dwFlags = RawInputDeviceFlags.RIDEV_INPUTSINK;
49 rid[i].hwndTarget = Handle;
52 rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.Consumer;
53 rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.Consumer.ConsumerControl;
54 rid[i].dwFlags = RawInputDeviceFlags.RIDEV_INPUTSINK;
55 rid[i].hwndTarget = Handle;
58 rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.Consumer;
59 rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.Consumer.Selection;
60 rid[i].dwFlags = RawInputDeviceFlags.RIDEV_INPUTSINK;
61 rid[i].hwndTarget = Handle;
64 rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.GenericDesktopControls;
65 rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.GenericDesktop.SystemControl;
66 rid[i].dwFlags = RawInputDeviceFlags.RIDEV_INPUTSINK;
67 rid[i].hwndTarget = Handle;
70 rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.GenericDesktopControls;
71 rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.GenericDesktop.GamePad;
72 rid[i].dwFlags = RawInputDeviceFlags.RIDEV_INPUTSINK;
73 rid[i].hwndTarget = Handle;
76 //rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.GenericDesktopControls;
77 //rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.GenericDesktop.Keyboard;
78 //rid[i].dwFlags = Const.RIDEV_EXINPUTSINK;
79 //rid[i].hwndTarget = Handle;
82 //rid[i].usUsagePage = (ushort)Hid.UsagePage.GenericDesktopControls;
83 //rid[i].usUsage = (ushort)Hid.UsageCollection.GenericDesktop.Mouse;
84 //rid[i].dwFlags = Const.RIDEV_EXINPUTSINK;
85 //rid[i].hwndTarget = aHWND;
88 iHidHandler = new SharpLib.Hid.Handler(rid);
89 if (!iHidHandler.IsRegistered)
91 Debug.WriteLine("Failed to register raw input devices: " + Marshal.GetLastWin32Error().ToString());
93 iHidHandler.OnHidEvent += HandleHidEventThreadSafe;
101 /// Here we receive HID events from our HID library.
103 /// <param name="aSender"></param>
104 /// <param name="aHidEvent"></param>
105 public void HandleHidEventThreadSafe(object aSender, SharpLib.Hid.Event aHidEvent)
107 if (aHidEvent.IsStray)
109 //Stray event just ignore it
113 if (this.InvokeRequired)
115 //Not in the proper thread, invoke ourselves
116 OnHidEventDelegate d = new OnHidEventDelegate(HandleHidEventThreadSafe);
117 this.Invoke(d, new object[] { aSender, aHidEvent });
121 if (aHidEvent.Usages.Count == 0)
123 //No usage, nothing to do then
127 //We are in the proper thread
128 if (aHidEvent.UsagePage == (ushort) Hid.UsagePage.WindowsMediaCenterRemoteControl)
130 switch (aHidEvent.Usages[0])
132 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.GreenStart:
135 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Eject:
136 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Ext2:
141 else if (aHidEvent.UsagePage == (ushort)Hid.UsagePage.Consumer)
143 //Keep this for debug when only ThinkPad keyboard is available
144 //if (aHidEvent.Usages[0] == (ushort)Hid.Usage.ConsumerControl.ThinkPadFullscreenMagnifier)
149 EventHidConsumerControl e = new EventHidConsumerControl {Usage = (Hid.Usage.ConsumerControl)aHidEvent.Usages[0]};
150 Properties.Settings.Default.EarManager.TriggerEvent(e);
161 /// <param name="aPrefix"></param>
162 private void CheckLastError(string aPrefix)
164 string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
165 Debug.WriteLine(aPrefix + Marshal.GetLastWin32Error().ToString() + ": " + errorMessage);
171 /// <param name="data"></param>
172 /// <returns></returns>
173 private IntPtr MarshalToPointer(object data)
175 IntPtr buf = Marshal.AllocHGlobal(
176 Marshal.SizeOf(data));
177 Marshal.StructureToPtr(data,
185 /// <returns></returns>
186 private SafeFileHandle OpenVolume(string aDriveName)
188 return Function.CreateFile("\\\\.\\" + aDriveName,
189 SharpLib.Win32.FileAccess.GENERIC_READ,
190 SharpLib.Win32.FileShare.FILE_SHARE_READ | SharpLib.Win32.FileShare.FILE_SHARE_WRITE,
192 CreationDisposition.OPEN_EXISTING,
200 /// <param name="aVolume"></param>
201 /// <returns></returns>
202 private bool LockVolume(SafeFileHandle aVolume)
204 //Hope that's doing what I think it does
205 IntPtr dwBytesReturned=new IntPtr();
206 //Should not be needed but I'm not sure how to pass NULL in there.
207 OVERLAPPED overlapped=new OVERLAPPED();
210 const int KMaxTries = 100;
211 const int KSleepTime = 10;
212 bool success = false;
214 while (!success && tries < KMaxTries)
216 success = Function.DeviceIoControl(aVolume, Const.FSCTL_LOCK_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
217 System.Threading.Thread.Sleep(KSleepTime);
221 CheckLastError("Lock volume: ");
229 /// <param name="aVolume"></param>
230 /// <returns></returns>
231 private bool DismountVolume(SafeFileHandle aVolume)
233 //Hope that's doing what I think it does
234 IntPtr dwBytesReturned = new IntPtr();
235 //Should not be needed but I'm not sure how to pass NULL in there.
236 OVERLAPPED overlapped=new OVERLAPPED();
238 bool res = Function.DeviceIoControl(aVolume, Const.FSCTL_DISMOUNT_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
239 CheckLastError("Dismount volume: ");
248 /// <param name="aVolume"></param>
249 /// <param name="aPreventRemoval"></param>
250 /// <returns></returns>
251 private bool PreventRemovalOfVolume(SafeFileHandle aVolume, bool aPreventRemoval)
253 //Hope that's doing what I think it does
254 IntPtr dwBytesReturned = new IntPtr();
255 //Should not be needed but I'm not sure how to pass NULL in there.
256 OVERLAPPED overlapped = new OVERLAPPED();
258 PREVENT_MEDIA_REMOVAL preventMediaRemoval = new PREVENT_MEDIA_REMOVAL();
259 preventMediaRemoval.PreventMediaRemoval = Convert.ToByte(aPreventRemoval);
260 IntPtr preventMediaRemovalParam = MarshalToPointer(preventMediaRemoval);
262 bool result = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_MEDIA_REMOVAL, preventMediaRemovalParam, Convert.ToUInt32(Marshal.SizeOf(preventMediaRemoval)), IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
263 CheckLastError("Media removal: ");
264 Marshal.FreeHGlobal(preventMediaRemovalParam);
270 /// Eject optical drive media opening the tray if any.
272 /// <param name="aVolume"></param>
273 /// <returns></returns>
274 private bool MediaEject(SafeFileHandle aVolume)
276 //Hope that's doing what I think it does
277 IntPtr dwBytesReturned = new IntPtr();
278 //Should not be needed but I'm not sure how to pass NULL in there.
279 OVERLAPPED overlapped=new OVERLAPPED();
281 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
282 CheckLastError("Media eject: ");
287 /// Close an optical drive tray.
289 /// <param name="aVolume"></param>
290 /// <returns></returns>
291 private bool MediaLoad(SafeFileHandle aVolume)
293 //Hope that's doing what I think it does
294 IntPtr dwBytesReturned = new IntPtr();
295 //Should not be needed but I'm not sure how to pass NULL in there.
296 OVERLAPPED overlapped=new OVERLAPPED();
298 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
299 CheckLastError("Media load: ");
306 /// <param name="aVolume"></param>
307 /// <returns></returns>
308 private bool StorageCheckVerify(SafeFileHandle aVolume)
310 //Hope that's doing what I think it does
311 IntPtr dwBytesReturned = new IntPtr();
312 //Should not be needed but I'm not sure how to pass NULL in there.
313 OVERLAPPED overlapped = new OVERLAPPED();
315 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_CHECK_VERIFY2, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
317 CheckLastError("Check verify: ");
325 /// Perform media ejection.
327 private void HandleEject()
329 string drive = ((FormMain)this).OpticalDriveToEject();
332 //Not a proper drive spec.
333 //Probably 'None' selected.
337 SafeFileHandle handle = OpenVolume(drive);
338 if (handle.IsInvalid)
340 CheckLastError("ERROR: Failed to open volume: ");
344 if (LockVolume(handle) && DismountVolume(handle))
346 Debug.WriteLine("Volume was dismounted.");
348 if (PreventRemovalOfVolume(handle,false))
350 //StorageCheckVerify(handle);
353 before = DateTime.Now;
354 bool ejectSuccess = MediaEject(handle);
355 double ms = (DateTime.Now - before).TotalMilliseconds;
357 //We assume that if it take more than a certain time to for eject to execute it means we actually ejected.
358 //If our eject completes too rapidly we assume the tray is already open and we will try to close it.
359 if (ejectSuccess && ms > 100)
361 Debug.WriteLine("Media was ejected");
363 else if (MediaLoad(handle))
365 Debug.WriteLine("Media was loaded");
371 Debug.WriteLine("Volume lock or dismount failed.");
374 //This is needed to make sure we can open the volume next time around
381 private void HandleGreenStart()
383 //First check if the process we want to launch already exists
384 string procName = Path.GetFileNameWithoutExtension(Properties.Settings.Default.StartFileName);
385 Process[] existingProcesses = Process.GetProcessesByName(procName);
386 if (existingProcesses == null || existingProcesses.Length == 0)
388 // Process do not exists just try to launch it
389 ProcessStartInfo start = new ProcessStartInfo();
390 // Enter in the command line arguments, everything you would enter after the executable name itself
391 //start.Arguments = arguments;
392 // Enter the executable to run, including the complete path
393 start.FileName = Properties.Settings.Default.StartFileName;
394 start.WindowStyle = ProcessWindowStyle.Normal;
395 start.CreateNoWindow = true;
396 start.UseShellExecute = true;
397 // Run the external process & wait for it to finish
398 Process proc = Process.Start(start);
400 //SL: We could have used that too
401 //Shell32.Shell shell = new Shell32.Shell();
402 //shell.ShellExecute(Properties.Settings.Default.StartFileName);
406 //This won't work properly until we have a manifest that enables uiAccess.
407 //However uiAccess just won't work with ClickOnce so we will have to use a different deployment system.
408 SwitchToThisWindow(existingProcesses[0].MainWindowHandle, true);
414 /// We need to handle WM_INPUT.
416 /// <param name="message"></param>
417 protected override void WndProc(ref Message message)
422 //Returning zero means we processed that message.
423 message.Result = new IntPtr(0);
424 iHidHandler.ProcessInput(ref message);
428 //Pass this on to base class.
429 base.WndProc(ref message);