Support Forums
[VB.NET] USB Listener - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Visual Basic and the .NET Framework (https://www.supportforums.net/forumdisplay.php?fid=19)
+---- Thread: [VB.NET] USB Listener (/showthread.php?tid=11922)



[VB.NET] USB Listener - wchar_t - 09-11-2010

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.;


RE: [VB.NET] USB Listener - -BoodyE- - 09-14-2010

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