Adding empty class for eject optical drive action.
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 //Trigger events as needed
131 EventHidWindowsMediaCenter e = new EventHidWindowsMediaCenter { Usage = (Hid.Usage.WindowsMediaCenterRemoteControl)aHidEvent.Usages[0] };
132 Properties.Settings.Default.EarManager.TriggerEvent(e);
134 //Old legacy hard coded stuff
136 switch (aHidEvent.Usages[0])
138 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.GreenStart:
141 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Eject:
142 case (ushort)Hid.Usage.WindowsMediaCenterRemoteControl.Ext2:
147 else if (aHidEvent.UsagePage == (ushort)Hid.UsagePage.Consumer)
149 EventHidConsumerControl e = new EventHidConsumerControl { Usage = (Hid.Usage.ConsumerControl)aHidEvent.Usages[0] };
150 Properties.Settings.Default.EarManager.TriggerEvent(e);
152 //Keep this for debug when only ThinkPad keyboard is available
153 //if (aHidEvent.Usages[0] == (ushort)Hid.Usage.ConsumerControl.ThinkPadFullscreenMagnifier)
165 /// <param name="aPrefix"></param>
166 private void CheckLastError(string aPrefix)
168 string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
169 Debug.WriteLine(aPrefix + Marshal.GetLastWin32Error().ToString() + ": " + errorMessage);
175 /// <param name="data"></param>
176 /// <returns></returns>
177 private IntPtr MarshalToPointer(object data)
179 IntPtr buf = Marshal.AllocHGlobal(
180 Marshal.SizeOf(data));
181 Marshal.StructureToPtr(data,
189 /// <returns></returns>
190 private SafeFileHandle OpenVolume(string aDriveName)
192 return Function.CreateFile("\\\\.\\" + aDriveName,
193 SharpLib.Win32.FileAccess.GENERIC_READ,
194 SharpLib.Win32.FileShare.FILE_SHARE_READ | SharpLib.Win32.FileShare.FILE_SHARE_WRITE,
196 CreationDisposition.OPEN_EXISTING,
204 /// <param name="aVolume"></param>
205 /// <returns></returns>
206 private bool LockVolume(SafeFileHandle aVolume)
208 //Hope that's doing what I think it does
209 IntPtr dwBytesReturned=new IntPtr();
210 //Should not be needed but I'm not sure how to pass NULL in there.
211 OVERLAPPED overlapped=new OVERLAPPED();
214 const int KMaxTries = 100;
215 const int KSleepTime = 10;
216 bool success = false;
218 while (!success && tries < KMaxTries)
220 success = Function.DeviceIoControl(aVolume, Const.FSCTL_LOCK_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
221 System.Threading.Thread.Sleep(KSleepTime);
225 CheckLastError("Lock volume: ");
233 /// <param name="aVolume"></param>
234 /// <returns></returns>
235 private bool DismountVolume(SafeFileHandle aVolume)
237 //Hope that's doing what I think it does
238 IntPtr dwBytesReturned = new IntPtr();
239 //Should not be needed but I'm not sure how to pass NULL in there.
240 OVERLAPPED overlapped=new OVERLAPPED();
242 bool res = Function.DeviceIoControl(aVolume, Const.FSCTL_DISMOUNT_VOLUME, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
243 CheckLastError("Dismount volume: ");
252 /// <param name="aVolume"></param>
253 /// <param name="aPreventRemoval"></param>
254 /// <returns></returns>
255 private bool PreventRemovalOfVolume(SafeFileHandle aVolume, bool aPreventRemoval)
257 //Hope that's doing what I think it does
258 IntPtr dwBytesReturned = new IntPtr();
259 //Should not be needed but I'm not sure how to pass NULL in there.
260 OVERLAPPED overlapped = new OVERLAPPED();
262 PREVENT_MEDIA_REMOVAL preventMediaRemoval = new PREVENT_MEDIA_REMOVAL();
263 preventMediaRemoval.PreventMediaRemoval = Convert.ToByte(aPreventRemoval);
264 IntPtr preventMediaRemovalParam = MarshalToPointer(preventMediaRemoval);
266 bool result = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_MEDIA_REMOVAL, preventMediaRemovalParam, Convert.ToUInt32(Marshal.SizeOf(preventMediaRemoval)), IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
267 CheckLastError("Media removal: ");
268 Marshal.FreeHGlobal(preventMediaRemovalParam);
274 /// Eject optical drive media opening the tray if any.
276 /// <param name="aVolume"></param>
277 /// <returns></returns>
278 private bool MediaEject(SafeFileHandle aVolume)
280 //Hope that's doing what I think it does
281 IntPtr dwBytesReturned = new IntPtr();
282 //Should not be needed but I'm not sure how to pass NULL in there.
283 OVERLAPPED overlapped=new OVERLAPPED();
285 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
286 CheckLastError("Media eject: ");
291 /// Close an optical drive tray.
293 /// <param name="aVolume"></param>
294 /// <returns></returns>
295 private bool MediaLoad(SafeFileHandle aVolume)
297 //Hope that's doing what I think it does
298 IntPtr dwBytesReturned = new IntPtr();
299 //Should not be needed but I'm not sure how to pass NULL in there.
300 OVERLAPPED overlapped=new OVERLAPPED();
302 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
303 CheckLastError("Media load: ");
310 /// <param name="aVolume"></param>
311 /// <returns></returns>
312 private bool StorageCheckVerify(SafeFileHandle aVolume)
314 //Hope that's doing what I think it does
315 IntPtr dwBytesReturned = new IntPtr();
316 //Should not be needed but I'm not sure how to pass NULL in there.
317 OVERLAPPED overlapped = new OVERLAPPED();
319 bool res = Function.DeviceIoControl(aVolume, Const.IOCTL_STORAGE_CHECK_VERIFY2, IntPtr.Zero, 0, IntPtr.Zero, 0, dwBytesReturned, ref overlapped);
321 CheckLastError("Check verify: ");
329 /// Perform media ejection.
331 private void HandleEject()
333 string drive = ((FormMain)this).OpticalDriveToEject();
336 //Not a proper drive spec.
337 //Probably 'None' selected.
341 SafeFileHandle handle = OpenVolume(drive);
342 if (handle.IsInvalid)
344 CheckLastError("ERROR: Failed to open volume: ");
348 if (LockVolume(handle) && DismountVolume(handle))
350 Debug.WriteLine("Volume was dismounted.");
352 if (PreventRemovalOfVolume(handle,false))
354 //StorageCheckVerify(handle);
357 before = DateTime.Now;
358 bool ejectSuccess = MediaEject(handle);
359 double ms = (DateTime.Now - before).TotalMilliseconds;
361 //We assume that if it take more than a certain time to for eject to execute it means we actually ejected.
362 //If our eject completes too rapidly we assume the tray is already open and we will try to close it.
363 if (ejectSuccess && ms > 100)
365 Debug.WriteLine("Media was ejected");
367 else if (MediaLoad(handle))
369 Debug.WriteLine("Media was loaded");
375 Debug.WriteLine("Volume lock or dismount failed.");
378 //This is needed to make sure we can open the volume next time around
385 private void HandleGreenStart()
387 //First check if the process we want to launch already exists
388 string procName = Path.GetFileNameWithoutExtension(Properties.Settings.Default.StartFileName);
389 Process[] existingProcesses = Process.GetProcessesByName(procName);
390 if (existingProcesses == null || existingProcesses.Length == 0)
392 // Process do not exists just try to launch it
393 ProcessStartInfo start = new ProcessStartInfo();
394 // Enter in the command line arguments, everything you would enter after the executable name itself
395 //start.Arguments = arguments;
396 // Enter the executable to run, including the complete path
397 start.FileName = Properties.Settings.Default.StartFileName;
398 start.WindowStyle = ProcessWindowStyle.Normal;
399 start.CreateNoWindow = true;
400 start.UseShellExecute = true;
401 // Run the external process & wait for it to finish
402 Process proc = Process.Start(start);
404 //SL: We could have used that too
405 //Shell32.Shell shell = new Shell32.Shell();
406 //shell.ShellExecute(Properties.Settings.Default.StartFileName);
410 //This won't work properly until we have a manifest that enables uiAccess.
411 //However uiAccess just won't work with ClickOnce so we will have to use a different deployment system.
412 SwitchToThisWindow(existingProcesses[0].MainWindowHandle, true);
418 /// We need to handle WM_INPUT.
420 /// <param name="message"></param>
421 protected override void WndProc(ref Message message)
426 //Returning zero means we processed that message.
427 message.Result = new IntPtr(0);
428 iHidHandler.ProcessInput(ref message);
432 //Pass this on to base class.
433 base.WndProc(ref message);