hola buenas
Tras leer el comentario de @Elektro en el otro tema(Hacer funcionar el lector de bandeja de discos con este lenguaje .net), decidí entrar aquí a ver el código de @Elektro.
Bueno, a mí tampoco me funcionaba el código de @Elektro pero conseguí que funcionara tras algunos cambios, especialmente con TimeSpan y ManagementBaseObject.
El caso es que ya me funciona y aquí dejo el código (que es un 99% del de @Elektro pero vamos
)
Pero antes algunos detalles,
- Desde NET, debe agregarse, desde 'agregar referencia' la librería System.Management
- La unidad de CD/DVD ROM debe contener un disco en su interior, de lo contrario este código no hace nada de nada.
NOTA: En ambos casos he usado el un proyecto "Aplicación de Windows Forms"
C#
VB.NET
Tras leer el comentario de @Elektro en el otro tema(Hacer funcionar el lector de bandeja de discos con este lenguaje .net), decidí entrar aquí a ver el código de @Elektro.
Bueno, a mí tampoco me funcionaba el código de @Elektro pero conseguí que funcionara tras algunos cambios, especialmente con TimeSpan y ManagementBaseObject.
El caso es que ya me funciona y aquí dejo el código (que es un 99% del de @Elektro pero vamos
![:P :P](https://forum.elhacker.net/Smileys/navidad/tongue.gif)
Pero antes algunos detalles,
- Desde NET, debe agregarse, desde 'agregar referencia' la librería System.Management
- La unidad de CD/DVD ROM debe contener un disco en su interior, de lo contrario este código no hace nada de nada.
NOTA: En ambos casos he usado el un proyecto "Aplicación de Windows Forms"
C#
Código (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private ManagementEventWatcher withEventsField_EventWatcher;
private ManagementEventWatcher EventWatcher
{
get { return withEventsField_EventWatcher; }
set
{
if (withEventsField_EventWatcher != null)
{
withEventsField_EventWatcher.EventArrived -= EventWatcher_EventArrived;
}
withEventsField_EventWatcher = value;
if (withEventsField_EventWatcher != null)
{
withEventsField_EventWatcher.EventArrived += EventWatcher_EventArrived;
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.EventWatcher.Dispose();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
WqlEventQuery eventQuery = new WqlEventQuery();
eventQuery.EventClassName = "__InstanceModificationEvent";
eventQuery.WithinInterval = new TimeSpan(0, 0, 1);
eventQuery.Condition = "TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";
EventWatcherOptions eventOptions = new EventWatcherOptions
{
BlockSize = 1,
Timeout = TimeSpan.MaxValue
};
ManagementPath scopePath = new ManagementPath
{
ClassName = "",
NamespacePath = "root\\CIMV2",
Path = "\\\\.\\root\\CIMV2",
Server = "."
};
ConnectionOptions scopeOptions = new ConnectionOptions
{
Authentication = AuthenticationLevel.Default,
EnablePrivileges = true,
Impersonation = ImpersonationLevel.Impersonate,
Timeout = TimeSpan.MaxValue
};
ManagementScope scope = new ManagementScope("\\root\\CIMV2", scopeOptions);
this.EventWatcher = new ManagementEventWatcher
{
Options = eventOptions,
Query = eventQuery,
Scope = scope
};
this.EventWatcher.Scope.Connect();
this.EventWatcher.Start();
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"];
string VolumeName = null;
string driveName = (string)wmiDevice["DeviceID"];
if (wmiDevice.Properties["VolumeName"].Value != null)
{
VolumeName = wmiDevice.Properties["VolumeName"].Value.ToString();
}
string Name = (string)wmiDevice["Name"];
StringBuilder infoMessage = new StringBuilder();
infoMessage.AppendLine(driveName);
infoMessage.AppendLine(VolumeName);
infoMessage.AppendLine(Name);
if (wmiDevice.Properties["VolumeName"].Value != null)
{
infoMessage.AppendLine("CD has been inserted");
}
else
{
infoMessage.AppendLine("CD has been ejected");
}
MessageBox.Show(infoMessage.ToString());
}
}
}
VB.NET
Código (vbnet) [Seleccionar]
Imports System.Management
Imports System.IO
Public Class Form1
Private WithEvents EventWatcher As ManagementEventWatcher
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim eventQuery As New WqlEventQuery()
eventQuery.EventClassName = "__InstanceModificationEvent"
eventQuery.WithinInterval = New TimeSpan(0, 0, 1)
eventQuery.Condition = "TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"
Dim eventOptions As New EventWatcherOptions With {
.BlockSize = 1,
.Timeout = TimeSpan.MaxValue
}
Dim scopePath As New ManagementPath With {
.ClassName = "",
.NamespacePath = "root\CIMV2",
.Path = "\\.\root\CIMV2",
.Server = "."
}
Dim scopeOptions As New ConnectionOptions With {
.Authentication = AuthenticationLevel.Default,
.EnablePrivileges = True,
.Impersonation = ImpersonationLevel.Impersonate,
.Timeout = TimeSpan.MaxValue
}
Dim scope As New ManagementScope("\root\CIMV2", scopeOptions)
Me.EventWatcher = New ManagementEventWatcher With {
.Options = eventOptions,
.Query = EventQuery,
.Scope = scope
}
Me.EventWatcher.Scope.Connect()
Me.EventWatcher.Start()
Catch ex As ManagementException
Console.WriteLine(ex.Message)
End Try
End Sub
Private Sub EventWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles EventWatcher.EventArrived
Dim wmiDevice As ManagementBaseObject = DirectCast(e.NewEvent("TargetInstance"), ManagementBaseObject)
Dim driveName As String = DirectCast(wmiDevice("DeviceID"), String)
Dim VolumeName As String = wmiDevice.Properties("VolumeName").Value
Dim Name As String = DirectCast(wmiDevice("Name"), String)
Dim infoMessage As New StringBuilder
infoMessage.AppendLine(driveName)
infoMessage.AppendLine(VolumeName)
infoMessage.AppendLine(Name)
If wmiDevice.Properties("VolumeName").Value IsNot Nothing Then
infoMessage.AppendLine("CD has been inserted")
Else
infoMessage.AppendLine("CD has been ejected")
End If
MessageBox.Show(infoMessage.ToString)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Me.EventWatcher.Dispose()
End Sub
End Class