Friday, January 19, 2007

console applicationt to detect USB

one guy in the fourm has asked about how to detect USB in a console application and here is the code.. Yes if cource it with some help of the google !!!!


Imports System.Management

Module Module1

Private WithEvents m_MediaConnectWatcher As Management.ManagementEventWatcher


Sub Main()

Dim query As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA ""Win32_DiskDrive""")
Dim watcher As New ManagementEventWatcher(query)

AddHandler watcher.EventArrived, AddressOf HandleEvent

' Start listening for events
watcher.Start()

Console.Read()

' Stop listening for events
watcher.Stop()
Return


End Sub


Private Sub HandleEvent(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived
Dim mbo, obj As ManagementBaseObject

' the first thing we have to do is figure out if this is a creation or deletion event
mbo = CType(e.NewEvent, ManagementBaseObject)
' next we need a copy of the instance that was either created or deleted
obj = CType(mbo("TargetInstance"), ManagementBaseObject)

Select Case mbo.ClassPath.ClassName
Case "__InstanceCreationEvent"
If obj("InterfaceType") = "USB" Then
MsgBox(obj("Caption") & " (Drive letter " & GetDriveLetterFromDisk(obj("Name")) & ") has been plugged in")
End If
Case "__InstanceDeletionEvent"
If obj("InterfaceType") = "USB" Then
MsgBox(obj("Caption") & " has been unplugged")
End If
End Select

End Sub

Private Function GetDriveLetterFromDisk(ByVal Name As String) As String
Dim oq_part, oq_disk As ObjectQuery
Dim mos_part, mos_disk As ManagementObjectSearcher
Dim obj_part, obj_disk As ManagementObject
Dim ans As String

' WMI queries use the "\" as an escape charcter
Name = Replace(Name, "\", "\\")

' First we map the Win32_DiskDrive instance with the association called
' Win32_DiskDriveToDiskPartition. Then we map the Win23_DiskPartion
' instance with the assocation called Win32_LogicalDiskToPartition

oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition")
mos_part = New ManagementObjectSearcher(oq_part)
For Each obj_part In mos_part.Get()

oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part("DeviceID") & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
mos_disk = New ManagementObjectSearcher(oq_disk)
For Each obj_disk In mos_disk.Get()
ans &= obj_disk("Name") & ","
Next
Next

Return ans.Trim(","c)
End Function

End Module

No comments: