Support Forums

Full Version: [VB.NET] USB Listener
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Code:
Imports System.Management, System.IO, System.Threading
Public Class USB_Watcher
    Private Shared Watcher As ManagementEventWatcher
    Public Shared Sub Start()
  Dim Events As WqlEventQuery : Dim scope = New ManagementScope("root\CIMV2") : scope.Options.EnablePrivileges = True : Try
    Events = New WqlEventQuery() : Events.EventClassName = "__InstanceCreationEvent" : Events.WithinInterval = New TimeSpan(0, 0, 3) : Events.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"
    Watcher = New ManagementEventWatcher(scope, Events) : AddHandler Watcher.EventArrived, AddressOf UsbInserted : Watcher.Start()
  Catch : If Watcher IsNot Nothing Then : Watcher.Stop() : End If : End Try
    End Sub
    Public Shared Sub UsbInserted(ByVal sender As Object, ByVal e As EventArgs)
  Dim drives As DriveInfo() = DriveInfo.GetDrives() : For Each drive As DriveInfo In drives
    If drive.DriveType = DriveType.Removable Then : Try '' drive.Name is The Removable Device Name
    MsgBox("Drive " + drive.Name + " Inserted...", MsgBoxStyle.Information, "USB Inserted!")
    Catch : Thread.Sleep(2000) : End Try : End If
    If Watcher IsNot Nothing Then : Watcher.Stop() : End If : Watcher.Start() : Next
    End Sub
End Class

A simple code I converted from c# on codeproject, and optimised.

to start an instance of the watcher call.

Code:
USB_Watcher.Start()
i stripped the events down to just an event of usb inserted.

credits to me.;
WOW, it is cool and new to me as I am new to vb.net Smile