Jump to content

Detect when a USB or W32disk is plugged in!

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Sharper_Software

Sharper_Software

    Newbie

  • Members
  • PipPip
  • 17 posts
Hey Guys just thought i'd write a quick doco on how to detect a usb when its inserted into your computer.

First off, this is the way the world of Google thinks you should do it:

Imports  System.Reflection
 Imports  System.IO
 Public Class Form1
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 ' Find the first  removable storage device and make this the initial
 '  directory if it exists
 Dim allDrives() As IO.DriveInfo = IO.DriveInfo.GetDrives()
 Dim d As IO.DriveInfo
 For Each d In allDrives
 If d.IsReady = True AndAlso d.DriveType = IO.DriveType.Removable Then
 ListBox1.Items.Add(d.VolumeLabel).ToString()
 If IO.DriveType.Removable Then
 TextBox1.Text = d.AvailableFreeSpace
 End If
 Else
 If d.IsReady = True And Not  d.DriveType = DriveType.Removable Then
 ListBox1.Items.Add(d.RootDirectory).ToString()
 TextBox1.Text = d.AvailableFreeSpace
 End If
 End If
 Next
 End Sub
 End Class
which is wrong to some degree, well it will work but it will consume to many resources in its constant checks for a usb drive because what its doing is:

-Get a list of all drives,
-Sort all the drives that are ready,
-Sort which drives are Removable.
-return a list.
and if you get more then one usb you are kinda screwed for locating a target.

Now if your like me and you want to know only when a new usb is inserted in your computer because u want to find out some piece of info on the disk then my way is the best way, well its not really all my way, i decompiled a usb virus and found some of this code haha use your enemy's weapons against them ay :-P

First you need the following imports:
Also Add a reference to (System.Management under ".NET")
'in VB 2008 Studio go to "Project tab" and click "Add Reference" then under the ".NET" Tab find "system.management"
'This is where we tell the application that we are going to setup a device management class.
Imports System.Management
Under "PUBLIC form1" or what ever you named your application, put:
Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
Public details As String 'the detail you want to extract from the event
Dim Targetdrive As String 'the drive that has triggered the event
Now we are going to put in place a MediaConnectWatcher that will inform the application of a new event created by a device.
  Public Sub StartDetection()
        ' __InstanceOperationEvent will trap both Creation and Deletion of class instances
        Dim query2 As String = "SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA ""Win32_DiskDrive"""
        m_MediaConnectWatcher = New ManagementEventWatcher(query2)
        m_MediaConnectWatcher.Start()
    End Sub
Ok now that our StartDetection process is defined we will get our events protocol in order:

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

        Dim mbo, obj As ManagementBaseObject

        'is  it a creation or deletion event
        mbo = CType(e.NewEvent, ManagementBaseObject)
        ' is it either created or deleted
        obj = CType(mbo("TargetInstance"), ManagementBaseObject)

        Select Case mbo.ClassPath.ClassName
            Case "__InstanceCreationEvent"
                If obj("InterfaceType") = "USB" Then
'put whatever code you want to run when you have a usb connected.
                    details = GetDriveLetterFromDisk(obj("Name"))
MsgBox("A New Device Was Connected at: " & details, 0, "New Device  Connected.")
                Else
                    MsgBox(obj("InterfaceType"))
                End If

                  
        End Select
Now we want to get our target when the event is triggered right? ok well we need the following:

 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
Alright now lucky last, add the following to the form's load event:

 StartDetection()
Now the way it will work with this approch is this:
-Application starts, Media connector now started.
-Application in Idle untill New W32.device has arrived.
-Application gets Target Disk Name.
-End cycle.

Under this process its not chewing up a heap of resources using a IO.Directory query like most people use, its also very handy for Autorun applications or media applications that you want to see if a new usb is inserted and if you want to import all the music into your library.

so i hope this helped some people, if you like +rep, if you don't please leave your CONSTRUCTIVE criticism below :sneaky:

Feel free to ask any questions

cheers :thumbup1:

#2
so1i

so1i

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 312 posts
This is cool, you should post it under VB.NET Tutorials :) but hey +rep here too :D

#3
Vswe

Vswe

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 9,552 posts
Great tutorial +rep

*moved to the tutorials section*