// --------------------------------------------------------------------------------------------------------------------
//
// This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
//
//
// Drive Detection Helper.
//
// --------------------------------------------------------------------------------------------------------------------
namespace HandBrakeWPF.Services
{
using System;
using System.Management;
using System.Threading;
using HandBrakeWPF.Services.Interfaces;
///
/// Drive Detection Helper.
///
public class DriveDetectService : IDriveDetectService
{
///
/// The watcher.
///
private ManagementEventWatcher watcher;
///
/// The detection action.
///
private Action detectionAction;
///
/// The start detection.
///
///
/// The detection Action.
///
public void StartDetection(Action action)
{
ThreadPool.QueueUserWorkItem(
delegate
{
this.detectionAction = action;
var options = new ConnectionOptions { EnablePrivileges = true };
var scope = new ManagementScope(@"root\CIMV2", options);
try
{
var query = new WqlEventQuery
{
EventClassName = "__InstanceModificationEvent",
WithinInterval = TimeSpan.FromSeconds(1),
Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5" // DriveType - 5: CDROM
};
this.watcher = new ManagementEventWatcher(scope, query);
this.watcher.EventArrived += this.WatcherEventArrived;
this.watcher.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
});
}
///
/// The close.
///
public void Close()
{
if (watcher != null)
{
this.watcher.Stop();
}
}
///
/// The watcher_ event arrived.
///
///
/// The sender.
///
///
/// The EventArrivedEventArgs.
///
private void WatcherEventArrived(object sender, EventArrivedEventArgs e)
{
if (this.detectionAction != null)
{
this.detectionAction();
}
}
}
}