Melhor maneira de detectar a inserção de dvd na unidade c #
Eu tentei usar o WMI para detectar nova inserção de mídia na unidade de disco usando o seguinte código. Mas existe solução gerenciada como o uso de loop no thread de plano de fundo com DriveInfo.GetDrives? Qual é a melhor maneira de fazer isso? Estou recebendo 'Disco não está na unidade, por favor insira disco' caixa de diálogo com abortar, tente novamente e continuar botão em outro pc quando eu tentei o código a seguir? Na máquina pode funcionar bem.
private void DriveWatcher()
{
try
{
var wqlEventQuery = new WqlEventQuery
{
EventClassName = "__InstanceModificationEvent",
WithinInterval = new TimeSpan(0, 0, 1),
Condition =
@"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"
};
var connectionOptions = new ConnectionOptions
{
EnablePrivileges = true,
Authority = null,
Authentication = AuthenticationLevel.Default
};
var managementScope = new ManagementScope("\\root\\CIMV2", connectionOptions);
ManagementEventWatcher = new ManagementEventWatcher(managementScope, wqlEventQuery);
ManagementEventWatcher.EventArrived += CdrEventArrived;
ManagementEventWatcher.Start();
}
catch (ManagementException e)
{
MessageBox.Show(e.Message, e.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CdrEventArrived(object sender, EventArrivedEventArgs e)
{
var wmiDevice = (ManagementBaseObject) e.NewEvent["TargetInstance"];
if (wmiDevice.Properties["VolumeName"].Value != null)
GetDrives();
else
GetDrives();
}
private void GetDrives()
{
if (InvokeRequired)
{
Invoke(new GetDrivesDelegate(GetDrives));
}
else
{
toolStripComboBoxDrives.Items.Clear();
DriveInfo[] drives = DriveInfo.GetDrives();
_drives = new Dictionary<string, DriveInfo>();
int selectedIndex = 0;
foreach (DriveInfo drive in drives)
{
if (drive.DriveType.Equals(DriveType.CDRom))
{
if (drive.IsReady)
{
string name = string.Format("{0} ({1})", drive.VolumeLabel, drive.Name.Substring(0, 2));
int selectedDrive = toolStripComboBoxDrives.Items.Add(name);
_drives.Add(name, drive);
selectedIndex = selectedDrive;
}
else
{
toolStripComboBoxDrives.Items.Add(drive.Name);
_drives.Add(drive.Name, drive);
}
}
}
toolStripComboBoxDrives.SelectedIndex = selectedIndex;
}
}
Basicamente, o que estou fazendo é em um evento chamado Load Watcher. Assim, quando o disco é inserido, o disco pronto será listado primeiro na caixa de combinação e o usuário poderá ejetar a unidade facilmente.