Server/FormMain.Hid.cs
author StephaneLenclud
Wed, 17 Aug 2016 16:39:36 +0200
changeset 237 1a1c2ae3a29c
parent 233 2b9541e54f7d
child 238 c92587ddabcd
permissions -rw-r--r--
Adding HID consumer control event.
     1 using System;
     2 using System.IO;
     3 using System.Collections.Generic;
     4 using System.Linq;
     5 using System.Text;
     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;
    12 //
    13 using Hid = SharpLib.Hid;
    14 using SharpLib.Win32;
    15 
    16 namespace SharpDisplayManager
    17 {
    18     /// <summary>
    19     /// Implement handling of HID input reports notably to be able to launch an application using the Green Start button from IR remotes.
    20     /// </summary>
    21     [System.ComponentModel.DesignerCategory("Code")]
    22     public class FormMainHid : Form
    23     {
    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);
    26         //
    27         public delegate void OnHidEventDelegate(object aSender, Hid.Event aHidEvent);
    28 
    29         /// <summary>
    30         /// Use notably to handle green start key from IR remote control
    31         /// </summary>
    32         private Hid.Handler iHidHandler;
    33 
    34         /// <summary>
    35         /// Register HID devices so that we receive corresponding WM_INPUT messages.
    36         /// </summary>
    37         protected void RegisterHidDevices()
    38         {
    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.
    42 
    43             RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[5];
    44 
    45             int i = 0;
    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;
    50 
    51             i++;
    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;
    56 
    57             i++;
    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;
    62 
    63             i++;
    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;
    68 
    69             i++;
    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;
    74 
    75             //i++;
    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;
    80 
    81             //i++;
    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;
    86 
    87 
    88             iHidHandler = new SharpLib.Hid.Handler(rid);
    89             if (!iHidHandler.IsRegistered)
    90             {
    91                 Debug.WriteLine("Failed to register raw input devices: " + Marshal.GetLastWin32Error().ToString());
    92             }
    93             iHidHandler.OnHidEvent += HandleHidEventThreadSafe;
    94 
    95         }
    96 
    97 
    98 
    99 
   100         /// <summary>
   101         /// Here we receive HID events from our HID library.
   102         /// </summary>
   103         /// <param name="aSender"></param>
   104         /// <param name="aHidEvent"></param>
   105         public void HandleHidEventThreadSafe(object aSender, SharpLib.Hid.Event aHidEvent)
   106         {
   107             if (aHidEvent.IsStray)
   108             {
   109                 //Stray event just ignore it
   110                 return;
   111             }
   112 
   113             if (this.InvokeRequired)
   114             {
   115                 //Not in the proper thread, invoke ourselves
   116                 OnHidEventDelegate d = new OnHidEventDelegate(HandleHidEventThreadSafe);
   117                 this.Invoke(d, new object[] { aSender, aHidEvent });
   118             }
   119             else
   120             {
   121                 if (aHidEvent.Usages.Count == 0)
   122                 {
   123                     //No usage, nothing to do then
   124                     return;
   125                 }
   126 
   127                 //We are in the proper thread
   128                 if (aHidEvent.UsagePage == (ushort) Hid.UsagePage.WindowsMediaCenterRemoteControl)
   129                 {
   130                     switch (aHidEvent.Usages[0])
   131                     {
   132                         case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.GreenStart:
   133                             HandleGreenStart();
   134                             break;
   135                         case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Eject:
   136                         case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Ext2:
   137                             HandleEject();
   138                             break;
   139                     }
   140                 }
   141                 else if (aHidEvent.UsagePage == (ushort)Hid.UsagePage.Consumer)
   142                 {
   143                     //Keep this for debug when only ThinkPad keyboard is available
   144                     //if (aHidEvent.Usages[0] == (ushort)Hid.Usage.ConsumerControl.ThinkPadFullscreenMagnifier)
   145                     //{
   146                     //    HandleEject();
   147                     //}
   148 
   149                     EventHidConsumerControl e = new EventHidConsumerControl {Usage = (Hid.Usage.ConsumerControl)aHidEvent.Usages[0]};
   150                     Properties.Settings.Default.EarManager.TriggerEvent(e);
   151 
   152 
   153                 }
   154 
   155             }
   156         }
   157 
   158         /// <summary>
   159         /// 
   160         /// </summary>
   161         /// <param name="aPrefix"></param>
   162         private void CheckLastError(string aPrefix)
   163         {
   164             string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
   165             Debug.WriteLine(aPrefix + Marshal.GetLastWin32Error().ToString() + ": " + errorMessage);
   166         }
   167 
   168         /// <summary>
   169         /// 
   170         /// </summary>
   171         /// <param name="data"></param>
   172         /// <returns></returns>
   173         private IntPtr MarshalToPointer(object data)
   174         {
   175             IntPtr buf = Marshal.AllocHGlobal(
   176                 Marshal.SizeOf(data));
   177             Marshal.StructureToPtr(data,
   178                 buf, false);
   179             return buf;
   180         }
   181 
   182         /// <summary>
   183         /// 
   184         /// </summary>
   185         /// <returns></returns>
   186         private SafeFileHandle OpenVolume(string aDriveName)
   187         {
   188             return Function.CreateFile("\\\\.\\" + aDriveName,
   189                                SharpLib.Win32.FileAccess.GENERIC_READ,
   190                                SharpLib.Win32.FileShare.FILE_SHARE_READ | SharpLib.Win32.FileShare.FILE_SHARE_WRITE,
   191                                IntPtr.Zero,
   192                                CreationDisposition.OPEN_EXISTING,
   193                                0,
   194                                IntPtr.Zero);
   195         }
   196 
   197         /// <summary>
   198         /// 
   199         /// </summary>
   200         /// <param name="aVolume"></param>
   201         /// <returns></returns>
   202         private bool LockVolume(SafeFileHandle aVolume)
   203         {
   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();
   208 
   209             int tries = 0;
   210             const int KMaxTries = 100;
   211             const int KSleepTime = 10;
   212             bool success = false;
   213 
   214             while (!success && tries < KMaxTries)
   215             {
   216                 success = Function.DeviceIoControl(aVolume, Const.FSCTL_LOCK_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   217                 System.Threading.Thread.Sleep(KSleepTime);
   218                 tries++;
   219             }
   220 
   221             CheckLastError("Lock volume: ");
   222 
   223             return success;
   224         }
   225 
   226         /// <summary>
   227         /// 
   228         /// </summary>
   229         /// <param name="aVolume"></param>
   230         /// <returns></returns>
   231         private bool DismountVolume(SafeFileHandle aVolume)
   232         {
   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();
   237 
   238             bool res = Function.DeviceIoControl(aVolume, Const.FSCTL_DISMOUNT_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   239             CheckLastError("Dismount volume: ");
   240             return res;
   241         }
   242 
   243 
   244 
   245         /// <summary>
   246         /// 
   247         /// </summary>
   248         /// <param name="aVolume"></param>
   249         /// <param name="aPreventRemoval"></param>
   250         /// <returns></returns>
   251         private bool PreventRemovalOfVolume(SafeFileHandle aVolume, bool aPreventRemoval)
   252         {
   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();
   257             //
   258             PREVENT_MEDIA_REMOVAL preventMediaRemoval = new PREVENT_MEDIA_REMOVAL();
   259             preventMediaRemoval.PreventMediaRemoval = Convert.ToByte(aPreventRemoval);
   260             IntPtr preventMediaRemovalParam = MarshalToPointer(preventMediaRemoval);
   261 
   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);
   265 
   266             return result;
   267         }
   268 
   269         /// <summary>
   270         /// Eject optical drive media opening the tray if any.
   271         /// </summary>
   272         /// <param name="aVolume"></param>
   273         /// <returns></returns>
   274         private bool MediaEject(SafeFileHandle aVolume)
   275         {
   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();
   280 
   281             bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   282             CheckLastError("Media eject: ");
   283             return res;
   284         }
   285 
   286         /// <summary>
   287         /// Close an optical drive tray.
   288         /// </summary>
   289         /// <param name="aVolume"></param>
   290         /// <returns></returns>
   291         private bool MediaLoad(SafeFileHandle aVolume)
   292         {
   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();
   297 
   298             bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   299             CheckLastError("Media load: ");
   300             return res;
   301         }
   302 
   303         /// <summary>
   304         /// 
   305         /// </summary>
   306         /// <param name="aVolume"></param>
   307         /// <returns></returns>
   308         private bool StorageCheckVerify(SafeFileHandle aVolume)
   309         {
   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();
   314 
   315             bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_CHECK_VERIFY2, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   316 
   317             CheckLastError("Check verify: ");
   318 
   319             return res;
   320         }        
   321         
   322 
   323 
   324         /// <summary>
   325         /// Perform media ejection.
   326         /// </summary>
   327         private void HandleEject()
   328         {
   329             string drive = ((FormMain)this).OpticalDriveToEject();
   330             if (drive.Length!=2)
   331             {
   332                 //Not a proper drive spec.
   333                 //Probably 'None' selected.
   334                 return;
   335             }
   336 
   337             SafeFileHandle handle = OpenVolume(drive);
   338             if (handle.IsInvalid)
   339             {
   340                 CheckLastError("ERROR: Failed to open volume: ");
   341                 return;
   342             }
   343 
   344             if (LockVolume(handle) && DismountVolume(handle))
   345             {
   346                 Debug.WriteLine("Volume was dismounted.");
   347 
   348                 if (PreventRemovalOfVolume(handle,false))
   349                 {
   350                     //StorageCheckVerify(handle);
   351 
   352                     DateTime before;
   353                     before = DateTime.Now;
   354                     bool ejectSuccess = MediaEject(handle);
   355                     double ms = (DateTime.Now - before).TotalMilliseconds;
   356 
   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)
   360                     {
   361                         Debug.WriteLine("Media was ejected");
   362                     }
   363                     else if (MediaLoad(handle))
   364                     {
   365                         Debug.WriteLine("Media was loaded");
   366                     }                    
   367                 }
   368             }
   369             else
   370             {
   371                 Debug.WriteLine("Volume lock or dismount failed.");
   372             }
   373 
   374             //This is needed to make sure we can open the volume next time around
   375             handle.Dispose();
   376         }
   377 
   378         /// <summary>
   379         /// 
   380         /// </summary>
   381         private void HandleGreenStart()
   382         {
   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)
   387             {
   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);
   399 
   400                 //SL: We could have used that too
   401                 //Shell32.Shell shell = new Shell32.Shell();
   402                 //shell.ShellExecute(Properties.Settings.Default.StartFileName);
   403             }
   404             else
   405             {
   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);
   409             }            
   410         }
   411 
   412 
   413         /// <summary>
   414         /// We need to handle WM_INPUT.
   415         /// </summary>
   416         /// <param name="message"></param>
   417         protected override void WndProc(ref Message message)
   418         {
   419             switch (message.Msg)
   420             {
   421                 case Const.WM_INPUT:
   422                     //Returning zero means we processed that message.
   423                     message.Result = new IntPtr(0);
   424                     iHidHandler.ProcessInput(ref message);
   425                     break;
   426             }
   427 
   428             //Pass this on to base class.
   429             base.WndProc(ref message);
   430         }
   431     }
   432 }