Saturday, September 17, 2011

VB.NET code to check USB drive Plugin

Imports System.Management

Public Class Form2

Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
Public USBDriveName As String
Public USBDriveLetter As String

Private Sub Form2_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed


End Sub

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


End Sub

Public Sub StartDetection()

Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'")

m_MediaConnectWatcher = New ManagementEventWatcher
m_MediaConnectWatcher.Query = query2

End Sub

Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived

Dim mbo As ManagementBaseObject
Dim obj As ManagementBaseObject

mbo = CType(e.NewEvent, ManagementBaseObject)
obj = CType(mbo("TargetInstance"), ManagementBaseObject)

Select Case mbo.ClassPath.ClassName
Case "__InstanceCreationEvent"
If obj.Item("InterfaceType").ToString = "USB" Then
USBDriveName = obj.Item("Caption").ToString
USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString)
MessageBox.Show(USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
End If
Case "__InstanceDeletionEvent"
If obj.Item("InterfaceType").ToString = "USB" Then
MessageBox.Show(USBDriveName & " was disconnected. " & USBDriveLetter & " is now inaccessible.") 'GetDriveLetterFromDisk(obj.Item("Name").ToString))
If obj.Item("Caption").ToString = USBDriveName Then
USBDriveLetter = ""
USBDriveName = ""
End If
End If
Case Else
MessageBox.Show("nope: " & obj.Item("Caption").ToString)
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 = ""

Name = Replace(Name, "\", "\\")

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.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
mos_disk = New ManagementObjectSearcher(oq_disk)
For Each obj_disk In mos_disk.Get()
ans &= obj_disk.Item("Name").ToString & ","

Return ans.Trim(","c)

End Function

End Class