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 private PowerManager.SettingNotifier iPowerSettingNotifier;
38 private Cec.Client iCecClient;
41 /// Register HID devices so that we receive corresponding WM_INPUT messages.
43 protected void RegisterHidDevices()
45 // Register the input device to receive the commands from the
46 // remote device. See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwmt/html/remote_control.asp
47 // for the vendor defined usage page.
49 RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[5];
52 rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.WindowsMediaCenterRemoteControl;
53 rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.WindowsMediaCenter.WindowsMediaCenterRemoteControl;
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.ConsumerControl;
60 rid[i].dwFlags = Const.RIDEV_INPUTSINK;
61 rid[i].hwndTarget = Handle;
64 rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.Consumer;
65 rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.Consumer.Selection;
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.SystemControl;
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.GamePad;
78 rid[i].dwFlags = Const.RIDEV_INPUTSINK;
79 rid[i].hwndTarget = Handle;
82 //rid[i].usUsagePage = (ushort)SharpLib.Hid.UsagePage.GenericDesktopControls;
83 //rid[i].usUsage = (ushort)SharpLib.Hid.UsageCollection.GenericDesktop.Keyboard;
84 //rid[i].dwFlags = Const.RIDEV_EXINPUTSINK;
85 //rid[i].hwndTarget = Handle;
88 //rid[i].usUsagePage = (ushort)Hid.UsagePage.GenericDesktopControls;
89 //rid[i].usUsage = (ushort)Hid.UsageCollection.GenericDesktop.Mouse;
90 //rid[i].dwFlags = Const.RIDEV_EXINPUTSINK;
91 //rid[i].hwndTarget = aHWND;
94 iHidHandler = new SharpLib.Hid.Handler(rid);
95 if (!iHidHandler.IsRegistered)
97 Debug.WriteLine("Failed to register raw input devices: " + Marshal.GetLastWin32Error().ToString());
99 iHidHandler.OnHidEvent += HandleHidEventThreadSafe;
101 //TODO: Move this some place else
102 iPowerSettingNotifier = new PowerManager.SettingNotifier(Handle);
103 iPowerSettingNotifier.OnMonitorPowerOn += MonitorPowerOn;
104 iPowerSettingNotifier.OnMonitorPowerOff += MonitorPowerOff;
107 iCecClient = new Cec.Client();
108 if (!iCecClient.Connect(1000))
110 Debug.WriteLine("WARNING: No CEC connection!");
114 void MonitorPowerOn()
116 Debug.WriteLine("ON");
117 iCecClient.PowerOnDevices(CecSharp.CecLogicalAddress.Tv);
120 void MonitorPowerOff()
122 Debug.WriteLine("OFF");
123 iCecClient.StandbyDevices(CecSharp.CecLogicalAddress.Tv);
128 /// Here we receive HID events from our HID library.
130 /// <param name="aSender"></param>
131 /// <param name="aHidEvent"></param>
132 public void HandleHidEventThreadSafe(object aSender, SharpLib.Hid.Event aHidEvent)
134 if (aHidEvent.IsStray)
136 //Stray event just ignore it
140 if (this.InvokeRequired)
142 //Not in the proper thread, invoke ourselves
143 OnHidEventDelegate d = new OnHidEventDelegate(HandleHidEventThreadSafe);
144 this.Invoke(d, new object[] { aSender, aHidEvent });
148 if (aHidEvent.Usages.Count == 0)
150 //No usage, nothing to do then
154 //We are in the proper thread
155 if (aHidEvent.UsagePage == (ushort) Hid.UsagePage.WindowsMediaCenterRemoteControl)
157 switch (aHidEvent.Usages[0])
159 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.GreenStart:
162 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Eject:
163 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Ext2:
169 //Keep this for debug when only ThinkPad keyboard is available
170 if (aHidEvent.UsagePage == (ushort)Hid.UsagePage.Consumer && aHidEvent.Usages[0] == (ushort)Hid.Usage.ConsumerControl.ThinkPadFullscreenMagnifier)
181 /// <param name="aPrefix"></param>
182 private void CheckLastError(string aPrefix)
184 string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
185 Debug.WriteLine(aPrefix + Marshal.GetLastWin32Error().ToString() + ": " + errorMessage);
191 /// <param name="data"></param>
192 /// <returns></returns>
193 private IntPtr MarshalToPointer(object data)
195 IntPtr buf = Marshal.AllocHGlobal(
196 Marshal.SizeOf(data));
197 Marshal.StructureToPtr(data,
205 /// <returns></returns>
206 private SafeFileHandle OpenVolume(string aDriveName)
208 return Function.CreateFile("\\\\.\\" + aDriveName,
209 SharpLib.Win32.FileAccess.GENERIC_READ,
210 SharpLib.Win32.FileShare.FILE_SHARE_READ | SharpLib.Win32.FileShare.FILE_SHARE_WRITE,
212 CreationDisposition.OPEN_EXISTING,
220 /// <param name="aVolume"></param>
221 /// <returns></returns>
222 private bool LockVolume(SafeFileHandle aVolume)
224 //Hope that's doing what I think it does
225 IntPtr dwBytesReturned=new IntPtr();
226 //Should not be needed but I'm not sure how to pass NULL in there.
227 OVERLAPPED overlapped=new OVERLAPPED();
230 const int KMaxTries = 100;
231 const int KSleepTime = 10;
232 bool success = false;
234 while (!success && tries < KMaxTries)
236 success = Function.DeviceIoControl(aVolume, Const.FSCTL_LOCK_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
237 System.Threading.Thread.Sleep(KSleepTime);
241 CheckLastError("Lock volume: ");
249 /// <param name="aVolume"></param>
250 /// <returns></returns>
251 private bool DismountVolume(SafeFileHandle aVolume)
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 bool res = Function.DeviceIoControl(aVolume, Const.FSCTL_DISMOUNT_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
259 CheckLastError("Dismount volume: ");
268 /// <param name="aVolume"></param>
269 /// <param name="aPreventRemoval"></param>
270 /// <returns></returns>
271 private bool PreventRemovalOfVolume(SafeFileHandle aVolume, bool aPreventRemoval)
273 //Hope that's doing what I think it does
274 IntPtr dwBytesReturned = new IntPtr();
275 //Should not be needed but I'm not sure how to pass NULL in there.
276 OVERLAPPED overlapped = new OVERLAPPED();
278 PREVENT_MEDIA_REMOVAL preventMediaRemoval = new PREVENT_MEDIA_REMOVAL();
279 preventMediaRemoval.PreventMediaRemoval = Convert.ToByte(aPreventRemoval);
280 IntPtr preventMediaRemovalParam = MarshalToPointer(preventMediaRemoval);
282 bool result = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_MEDIA_REMOVAL, preventMediaRemovalParam, Convert.ToUInt32(Marshal.SizeOf(preventMediaRemoval)), IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
283 CheckLastError("Media removal: ");
284 Marshal.FreeHGlobal(preventMediaRemovalParam);
290 /// Eject optical drive media opening the tray if any.
292 /// <param name="aVolume"></param>
293 /// <returns></returns>
294 private bool MediaEject(SafeFileHandle aVolume)
296 //Hope that's doing what I think it does
297 IntPtr dwBytesReturned = new IntPtr();
298 //Should not be needed but I'm not sure how to pass NULL in there.
299 OVERLAPPED overlapped=new OVERLAPPED();
301 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
302 CheckLastError("Media eject: ");
307 /// Close an optical drive tray.
309 /// <param name="aVolume"></param>
310 /// <returns></returns>
311 private bool MediaLoad(SafeFileHandle aVolume)
313 //Hope that's doing what I think it does
314 IntPtr dwBytesReturned = new IntPtr();
315 //Should not be needed but I'm not sure how to pass NULL in there.
316 OVERLAPPED overlapped=new OVERLAPPED();
318 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
319 CheckLastError("Media load: ");
326 /// <param name="aVolume"></param>
327 /// <returns></returns>
328 private bool StorageCheckVerify(SafeFileHandle aVolume)
330 //Hope that's doing what I think it does
331 IntPtr dwBytesReturned = new IntPtr();
332 //Should not be needed but I'm not sure how to pass NULL in there.
333 OVERLAPPED overlapped = new OVERLAPPED();
335 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_CHECK_VERIFY2, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
337 CheckLastError("Check verify: ");
345 /// Perform media ejection.
347 private void HandleEject()
349 string drive = ((MainForm)this).OpticalDriveToEject();
352 //Not a proper drive spec.
353 //Probably 'None' selected.
357 SafeFileHandle handle = OpenVolume(drive);
358 if (handle.IsInvalid)
360 CheckLastError("ERROR: Failed to open volume: ");
364 if (LockVolume(handle) && DismountVolume(handle))
366 Debug.WriteLine("Volume was dismounted.");
368 if (PreventRemovalOfVolume(handle,false))
370 //StorageCheckVerify(handle);
373 before = DateTime.Now;
374 bool ejectSuccess = MediaEject(handle);
375 double ms = (DateTime.Now - before).TotalMilliseconds;
377 //We assume that if it take more than a certain time to for eject to execute it means we actually ejected.
378 //If our eject completes too rapidly we assume the tray is already open and we will try to close it.
379 if (ejectSuccess && ms > 100)
381 Debug.WriteLine("Media was ejected");
383 else if (MediaLoad(handle))
385 Debug.WriteLine("Media was loaded");
391 Debug.WriteLine("Volume lock or dismount failed.");
394 //This is needed to make sure we can open the volume next time around
401 private void HandleGreenStart()
403 //First check if the process we want to launch already exists
404 string procName = Path.GetFileNameWithoutExtension(Properties.Settings.Default.StartFileName);
405 Process[] existingProcesses = Process.GetProcessesByName(procName);
406 if (existingProcesses == null || existingProcesses.Length == 0)
408 // Process do not exists just try to launch it
409 ProcessStartInfo start = new ProcessStartInfo();
410 // Enter in the command line arguments, everything you would enter after the executable name itself
411 //start.Arguments = arguments;
412 // Enter the executable to run, including the complete path
413 start.FileName = Properties.Settings.Default.StartFileName;
414 start.WindowStyle = ProcessWindowStyle.Normal;
415 start.CreateNoWindow = true;
416 start.UseShellExecute = true;
417 // Run the external process & wait for it to finish
418 Process proc = Process.Start(start);
420 //SL: We could have used that too
421 //Shell32.Shell shell = new Shell32.Shell();
422 //shell.ShellExecute(Properties.Settings.Default.StartFileName);
426 //This won't work properly until we have a manifest that enables uiAccess.
427 //However uiAccess just won't work with ClickOnce so we will have to use a different deployment system.
428 SwitchToThisWindow(existingProcesses[0].MainWindowHandle, true);
432 /// We need to handle WM_INPUT.
434 /// <param name="message"></param>
435 protected override void WndProc(ref Message message)
440 //Returning zero means we processed that message.
441 message.Result = new IntPtr(0);
442 iHidHandler.ProcessInput(ref message);
446 //Hook in our power manager
447 if (iPowerSettingNotifier!=null)
449 iPowerSettingNotifier.WndProc(ref message);
452 //Is that needed? Check the docs.
453 base.WndProc(ref message);