.NET Conversions - VB.NET Detect CD-ROM Insert and Eject
Detect CD_ROM actions - C# to VB.NET
Synopsis:
Listed below is code used to detect the insertion into or ejection from a CDROM device. The original C# code can be found at http://www.publicjoe.f9.co.uk/csharp/snip/snip002.html. To run the code below a reference to the system.management dll must be added and the project must be set up to run as a Console application with the startup object set to Sub Main.
Solution:
Imports System Imports System.Management Class WMIEvent Shared Sub Main(ByVal args() As String) Dim we As New WMIEvent Dim w As ManagementEventWatcher = Nothing Dim q As WqlEventQuery Dim observer As New ManagementOperationObserver ' Bind to local machine Dim opt As New ConnectionOptions opt.EnablePrivileges = True 'sets required privilege Dim scope As New ManagementScope("root\CIMV2", opt) Try q = New WqlEventQuery q.EventClassName = "__InstanceModificationEvent" q.WithinInterval = New TimeSpan(0, 0, 1) ' DriveType - 5: CDROM q.Condition = "TargetInstance ISA 'Win32_LogicalDisk'" & _ " and TargetInstance.DriveType = 5" w = New ManagementEventWatcher(scope, q) ' register async. event handler AddHandler w.EventArrived, AddressOf we.CDREventArrived w.Start() ' Do something usefull,block thread for testing Console.ReadLine() Catch e As Exception Console.WriteLine(e.Message) Finally w.Stop() End Try End Sub 'Main ' Dump all properties Public Sub CDREventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs) ' Get the Event object and display it Dim pd As PropertyData = e.NewEvent.Properties("TargetInstance") If Not (pd Is Nothing) Then Dim mbo As ManagementBaseObject = pd.Value ' 'ToDo: Error processing original source shown below ' { ' ManagementBaseObject mbo = pd.Value as ManagementBaseObject; '---------------------------------------------^--- Syntax error: ';' expected ' if CD removed VolumeName == null If Not (mbo.Properties("VolumeName").Value Is Nothing) Then Console.WriteLine("CD has been inserted") Else Console.WriteLine("CD has been ejected") End If End If End Sub 'CDREventArrived End Class 'WMIEvent