Prototype for event and action framework.
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 MainFormHid : 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 = Const.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 = Const.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 = Const.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 = Const.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 = Const.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:
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)
154 /// <param name="aPrefix"></param>
155 private void CheckLastError(string aPrefix)
157 string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
158 Debug.WriteLine(aPrefix + Marshal.GetLastWin32Error().ToString() + ": " + errorMessage);
164 /// <param name="data"></param>
165 /// <returns></returns>
166 private IntPtr MarshalToPointer(object data)
168 IntPtr buf = Marshal.AllocHGlobal(
169 Marshal.SizeOf(data));
170 Marshal.StructureToPtr(data,
178 /// <returns></returns>
179 private SafeFileHandle OpenVolume(string aDriveName)
181 return Function.CreateFile("\\\\.\\" + aDriveName,
182 SharpLib.Win32.FileAccess.GENERIC_READ,
183 SharpLib.Win32.FileShare.FILE_SHARE_READ | SharpLib.Win32.FileShare.FILE_SHARE_WRITE,
185 CreationDisposition.OPEN_EXISTING,
193 /// <param name="aVolume"></param>
194 /// <returns></returns>
195 private bool LockVolume(SafeFileHandle aVolume)
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();
203 const int KMaxTries = 100;
204 const int KSleepTime = 10;
205 bool success = false;
207 while (!success && tries < KMaxTries)
209 success = Function.DeviceIoControl(aVolume, Const.FSCTL_LOCK_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
210 System.Threading.Thread.Sleep(KSleepTime);
214 CheckLastError("Lock volume: ");
222 /// <param name="aVolume"></param>
223 /// <returns></returns>
224 private bool DismountVolume(SafeFileHandle aVolume)
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();
231 bool res = Function.DeviceIoControl(aVolume, Const.FSCTL_DISMOUNT_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
232 CheckLastError("Dismount volume: ");
241 /// <param name="aVolume"></param>
242 /// <param name="aPreventRemoval"></param>
243 /// <returns></returns>
244 private bool PreventRemovalOfVolume(SafeFileHandle aVolume, bool aPreventRemoval)
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();
251 PREVENT_MEDIA_REMOVAL preventMediaRemoval = new PREVENT_MEDIA_REMOVAL();
252 preventMediaRemoval.PreventMediaRemoval = Convert.ToByte(aPreventRemoval);
253 IntPtr preventMediaRemovalParam = MarshalToPointer(preventMediaRemoval);
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);
263 /// Eject optical drive media opening the tray if any.
265 /// <param name="aVolume"></param>
266 /// <returns></returns>
267 private bool MediaEject(SafeFileHandle aVolume)
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();
274 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
275 CheckLastError("Media eject: ");
280 /// Close an optical drive tray.
282 /// <param name="aVolume"></param>
283 /// <returns></returns>
284 private bool MediaLoad(SafeFileHandle aVolume)
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();
291 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
292 CheckLastError("Media load: ");
299 /// <param name="aVolume"></param>
300 /// <returns></returns>
301 private bool StorageCheckVerify(SafeFileHandle aVolume)
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();
308 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_CHECK_VERIFY2, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
310 CheckLastError("Check verify: ");
318 /// Perform media ejection.
320 private void HandleEject()
322 string drive = ((MainForm)this).OpticalDriveToEject();
325 //Not a proper drive spec.
326 //Probably 'None' selected.
330 SafeFileHandle handle = OpenVolume(drive);
331 if (handle.IsInvalid)
333 CheckLastError("ERROR: Failed to open volume: ");
337 if (LockVolume(handle) && DismountVolume(handle))
339 Debug.WriteLine("Volume was dismounted.");
341 if (PreventRemovalOfVolume(handle,false))
343 //StorageCheckVerify(handle);
346 before = DateTime.Now;
347 bool ejectSuccess = MediaEject(handle);
348 double ms = (DateTime.Now - before).TotalMilliseconds;
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)
354 Debug.WriteLine("Media was ejected");
356 else if (MediaLoad(handle))
358 Debug.WriteLine("Media was loaded");
364 Debug.WriteLine("Volume lock or dismount failed.");
367 //This is needed to make sure we can open the volume next time around
374 private void HandleGreenStart()
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)
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);
393 //SL: We could have used that too
394 //Shell32.Shell shell = new Shell32.Shell();
395 //shell.ShellExecute(Properties.Settings.Default.StartFileName);
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);
407 /// We need to handle WM_INPUT.
409 /// <param name="message"></param>
410 protected override void WndProc(ref Message message)
415 //Returning zero means we processed that message.
416 message.Result = new IntPtr(0);
417 iHidHandler.ProcessInput(ref message);
421 //Pass this on to base class.
422 base.WndProc(ref message);