Server/MainForm.Hid.cs
author StephaneLenclud
Fri, 22 Jan 2016 16:08:22 +0100
changeset 183 e9a5dc5092fd
parent 161 7b19bea5d73a
permissions -rw-r--r--
Support for recording text.
     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 MainFormHid : 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 = Const.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 = Const.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 = Const.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 = Const.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 = Const.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 
   142                 //Keep this for debug when only ThinkPad keyboard is available
   143                 if (aHidEvent.UsagePage == (ushort)Hid.UsagePage.Consumer && aHidEvent.Usages[0] == (ushort)Hid.Usage.ConsumerControl.ThinkPadFullscreenMagnifier)
   144                 {
   145                     HandleEject();
   146                 }
   147 
   148             }
   149         }
   150 
   151         /// <summary>
   152         /// 
   153         /// </summary>
   154         /// <param name="aPrefix"></param>
   155         private void CheckLastError(string aPrefix)
   156         {
   157             string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
   158             Debug.WriteLine(aPrefix + Marshal.GetLastWin32Error().ToString() + ": " + errorMessage);
   159         }
   160 
   161         /// <summary>
   162         /// 
   163         /// </summary>
   164         /// <param name="data"></param>
   165         /// <returns></returns>
   166         private IntPtr MarshalToPointer(object data)
   167         {
   168             IntPtr buf = Marshal.AllocHGlobal(
   169                 Marshal.SizeOf(data));
   170             Marshal.StructureToPtr(data,
   171                 buf, false);
   172             return buf;
   173         }
   174 
   175         /// <summary>
   176         /// 
   177         /// </summary>
   178         /// <returns></returns>
   179         private SafeFileHandle OpenVolume(string aDriveName)
   180         {
   181             return Function.CreateFile("\\\\.\\" + aDriveName,
   182                                SharpLib.Win32.FileAccess.GENERIC_READ,
   183                                SharpLib.Win32.FileShare.FILE_SHARE_READ | SharpLib.Win32.FileShare.FILE_SHARE_WRITE,
   184                                IntPtr.Zero,
   185                                CreationDisposition.OPEN_EXISTING,
   186                                0,
   187                                IntPtr.Zero);
   188         }
   189 
   190         /// <summary>
   191         /// 
   192         /// </summary>
   193         /// <param name="aVolume"></param>
   194         /// <returns></returns>
   195         private bool LockVolume(SafeFileHandle aVolume)
   196         {
   197             //Hope that's doing what I think it does
   198             IntPtr dwBytesReturned=new IntPtr();
   199             //Should not be needed but I'm not sure how to pass NULL in there.
   200             OVERLAPPED overlapped=new OVERLAPPED();
   201 
   202             int tries = 0;
   203             const int KMaxTries = 100;
   204             const int KSleepTime = 10;
   205             bool success = false;
   206 
   207             while (!success && tries < KMaxTries)
   208             {
   209                 success = Function.DeviceIoControl(aVolume, Const.FSCTL_LOCK_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   210                 System.Threading.Thread.Sleep(KSleepTime);
   211                 tries++;
   212             }
   213 
   214             CheckLastError("Lock volume: ");
   215 
   216             return success;
   217         }
   218 
   219         /// <summary>
   220         /// 
   221         /// </summary>
   222         /// <param name="aVolume"></param>
   223         /// <returns></returns>
   224         private bool DismountVolume(SafeFileHandle aVolume)
   225         {
   226             //Hope that's doing what I think it does
   227             IntPtr dwBytesReturned = new IntPtr();
   228             //Should not be needed but I'm not sure how to pass NULL in there.
   229             OVERLAPPED overlapped=new OVERLAPPED();
   230 
   231             bool res = Function.DeviceIoControl(aVolume, Const.FSCTL_DISMOUNT_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   232             CheckLastError("Dismount volume: ");
   233             return res;
   234         }
   235 
   236 
   237 
   238         /// <summary>
   239         /// 
   240         /// </summary>
   241         /// <param name="aVolume"></param>
   242         /// <param name="aPreventRemoval"></param>
   243         /// <returns></returns>
   244         private bool PreventRemovalOfVolume(SafeFileHandle aVolume, bool aPreventRemoval)
   245         {
   246             //Hope that's doing what I think it does
   247             IntPtr dwBytesReturned = new IntPtr();
   248             //Should not be needed but I'm not sure how to pass NULL in there.
   249             OVERLAPPED overlapped = new OVERLAPPED();
   250             //
   251             PREVENT_MEDIA_REMOVAL preventMediaRemoval = new PREVENT_MEDIA_REMOVAL();
   252             preventMediaRemoval.PreventMediaRemoval = Convert.ToByte(aPreventRemoval);
   253             IntPtr preventMediaRemovalParam = MarshalToPointer(preventMediaRemoval);
   254 
   255             bool result = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_MEDIA_REMOVAL, preventMediaRemovalParam, Convert.ToUInt32(Marshal.SizeOf(preventMediaRemoval)), IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   256             CheckLastError("Media removal: ");
   257             Marshal.FreeHGlobal(preventMediaRemovalParam);
   258 
   259             return result;
   260         }
   261 
   262         /// <summary>
   263         /// Eject optical drive media opening the tray if any.
   264         /// </summary>
   265         /// <param name="aVolume"></param>
   266         /// <returns></returns>
   267         private bool MediaEject(SafeFileHandle aVolume)
   268         {
   269             //Hope that's doing what I think it does
   270             IntPtr dwBytesReturned = new IntPtr();
   271             //Should not be needed but I'm not sure how to pass NULL in there.
   272             OVERLAPPED overlapped=new OVERLAPPED();
   273 
   274             bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   275             CheckLastError("Media eject: ");
   276             return res;
   277         }
   278 
   279         /// <summary>
   280         /// Close an optical drive tray.
   281         /// </summary>
   282         /// <param name="aVolume"></param>
   283         /// <returns></returns>
   284         private bool MediaLoad(SafeFileHandle aVolume)
   285         {
   286             //Hope that's doing what I think it does
   287             IntPtr dwBytesReturned = new IntPtr();
   288             //Should not be needed but I'm not sure how to pass NULL in there.
   289             OVERLAPPED overlapped=new OVERLAPPED();
   290 
   291             bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   292             CheckLastError("Media load: ");
   293             return res;
   294         }
   295 
   296         /// <summary>
   297         /// 
   298         /// </summary>
   299         /// <param name="aVolume"></param>
   300         /// <returns></returns>
   301         private bool StorageCheckVerify(SafeFileHandle aVolume)
   302         {
   303             //Hope that's doing what I think it does
   304             IntPtr dwBytesReturned = new IntPtr();
   305             //Should not be needed but I'm not sure how to pass NULL in there.
   306             OVERLAPPED overlapped = new OVERLAPPED();
   307 
   308             bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_CHECK_VERIFY2, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
   309 
   310             CheckLastError("Check verify: ");
   311 
   312             return res;
   313         }        
   314         
   315 
   316 
   317         /// <summary>
   318         /// Perform media ejection.
   319         /// </summary>
   320         private void HandleEject()
   321         {
   322             string drive = ((MainForm)this).OpticalDriveToEject();
   323             if (drive.Length!=2)
   324             {
   325                 //Not a proper drive spec.
   326                 //Probably 'None' selected.
   327                 return;
   328             }
   329 
   330             SafeFileHandle handle = OpenVolume(drive);
   331             if (handle.IsInvalid)
   332             {
   333                 CheckLastError("ERROR: Failed to open volume: ");
   334                 return;
   335             }
   336 
   337             if (LockVolume(handle) && DismountVolume(handle))
   338             {
   339                 Debug.WriteLine("Volume was dismounted.");
   340 
   341                 if (PreventRemovalOfVolume(handle,false))
   342                 {
   343                     //StorageCheckVerify(handle);
   344 
   345                     DateTime before;
   346                     before = DateTime.Now;
   347                     bool ejectSuccess = MediaEject(handle);
   348                     double ms = (DateTime.Now - before).TotalMilliseconds;
   349 
   350                     //We assume that if it take more than a certain time to for eject to execute it means we actually ejected.
   351                     //If our eject completes too rapidly we assume the tray is already open and we will try to close it. 
   352                     if (ejectSuccess && ms > 100)
   353                     {
   354                         Debug.WriteLine("Media was ejected");
   355                     }
   356                     else if (MediaLoad(handle))
   357                     {
   358                         Debug.WriteLine("Media was loaded");
   359                     }                    
   360                 }
   361             }
   362             else
   363             {
   364                 Debug.WriteLine("Volume lock or dismount failed.");
   365             }
   366 
   367             //This is needed to make sure we can open the volume next time around
   368             handle.Dispose();
   369         }
   370 
   371         /// <summary>
   372         /// 
   373         /// </summary>
   374         private void HandleGreenStart()
   375         {
   376             //First check if the process we want to launch already exists
   377             string procName = Path.GetFileNameWithoutExtension(Properties.Settings.Default.StartFileName);
   378             Process[] existingProcesses = Process.GetProcessesByName(procName);
   379             if (existingProcesses == null || existingProcesses.Length == 0)
   380             {
   381                 // Process do not exists just try to launch it
   382                 ProcessStartInfo start = new ProcessStartInfo();
   383                 // Enter in the command line arguments, everything you would enter after the executable name itself
   384                 //start.Arguments = arguments; 
   385                 // Enter the executable to run, including the complete path
   386                 start.FileName = Properties.Settings.Default.StartFileName;
   387                 start.WindowStyle = ProcessWindowStyle.Normal;
   388                 start.CreateNoWindow = true;
   389                 start.UseShellExecute = true;
   390                 // Run the external process & wait for it to finish
   391                 Process proc = Process.Start(start);
   392 
   393                 //SL: We could have used that too
   394                 //Shell32.Shell shell = new Shell32.Shell();
   395                 //shell.ShellExecute(Properties.Settings.Default.StartFileName);
   396             }
   397             else
   398             {
   399                 //This won't work properly until we have a manifest that enables uiAccess.
   400                 //However uiAccess just won't work with ClickOnce so we will have to use a different deployment system.
   401                 SwitchToThisWindow(existingProcesses[0].MainWindowHandle, true);
   402             }            
   403         }
   404 
   405 
   406         /// <summary>
   407         /// We need to handle WM_INPUT.
   408         /// </summary>
   409         /// <param name="message"></param>
   410         protected override void WndProc(ref Message message)
   411         {
   412             switch (message.Msg)
   413             {
   414                 case Const.WM_INPUT:
   415                     //Returning zero means we processed that message.
   416                     message.Result = new IntPtr(0);
   417                     iHidHandler.ProcessInput(ref message);
   418                     break;
   419             }
   420 
   421             //Pass this on to base class.
   422             base.WndProc(ref message);
   423         }
   424     }
   425 }