+ Reply to Thread
Results 1 to 3 of 3

Thread: Detect when a USB or W32disk is plugged in!

  1. #1
    Join Date
    Mar 2010
    Location
    Melbourne, Australia
    Posts
    17
    Blog Entries
    1
    Rep Power
    8

    Lightbulb Detect when a USB or W32disk is plugged in!

    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:

    Code:
    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

    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.
    Code:
    Imports System.Management
    Under "PUBLIC form1" or what ever you named your application, put:
    Code:
    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.
    Code:
      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:

    Code:
        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:

    Code:
     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:

    Code:
     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

    Feel free to ask any questions

    cheers

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    so1i's Avatar
    so1i is offline Programming Professional
    Join Date
    Sep 2009
    Location
    Aberystwyth, United Kingdom
    Posts
    309
    Rep Power
    0

    Re: Detect when a USB or W32disk is plugged in!

    This is cool, you should post it under VB.NET Tutorials but hey +rep here too

  4. #3
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    Re: Detect when a USB or W32disk is plugged in!

    Great tutorial +rep

    *moved to the tutorials section*

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Is it possible to detect an usb device when the device is plugged in??
    By yonghan in forum Visual Basic Programming
    Replies: 6
    Last Post: 02-07-2011, 04:47 AM
  2. External Hard Drive Always Plugged In?
    By TcM in forum Technology Ramble
    Replies: 7
    Last Post: 10-24-2010, 05:41 PM
  3. Detect the error
    By hbk in forum C and C++
    Replies: 5
    Last Post: 03-14-2010, 03:37 PM
  4. Detect Character Set
    By dargueta in forum General Programming
    Replies: 14
    Last Post: 09-10-2009, 02:55 PM
  5. How to detect if it's debian etc..?
    By HappyUser in forum Linux/Unix General
    Replies: 3
    Last Post: 08-14-2008, 10:31 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts