Detect when Removable USB Volume Drive Devices are Attached or Removed – VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (11 votes, average: 4.36 out of 5)
 

Below is some code I saw on a vb message board along time ago but I can’t remember where. It may have been vbforums.com. I made some code changes and then tested the code to have it throw a messagebox with the drive letter of the new usb device being attached or removed. It uses application subclassing to intercept the messages and checks if any are activated by a removable volume being Removed, Inserted, Attached, etc.. If it is then it will parse the volume drive letter of the device and throw a messagebox letting you know. USB devices like flash drives (Thumb Drives or Pen Drive’s as they are also called), external hard drives, etc. with a removable disk volume should be detected just fine. My testing recognized different usb volumes with no problems. You can use this code with VB.NET, Visual Basic 2008, VB 2010, 2013, etc. to check for both the arrival of usb volume devices and the removal. You can also make some changes to make it work for VB 6.0 as well. Visual Basic 6.0 will need an addiional API call or two for the subclassing portion.


These go in your declaration section of your program.

    '
    'The messages to look for.
    Private Const WM_DEVICECHANGE As Integer = &H219
    Private Const DBT_DEVICEARRIVAL As Integer = &H8000
    Private Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004
    Private Const DBT_DEVTYP_VOLUME As Integer = &H2  '
    '
    'Get the information about the detected volume.
    Private Structure DEV_BROADCAST_VOLUME

        Dim Dbcv_Size As Integer

        Dim Dbcv_Devicetype As Integer

        Dim Dbcv_Reserved As Integer

        Dim Dbcv_Unitmask As Integer

        Dim Dbcv_Flags As Short

    End Structure

 

Now for the subclassing based code. This is where it starts to get alittle difficult…

    Protected Overrides Sub WndProc(ByRef M As System.Windows.Forms.Message)
        '
        'These are the required subclassing codes for detecting device based removal and arrival.
        '
        If M.Msg = WM_DEVICECHANGE Then

            Select Case M.WParam
                '
                'Check if a device was added.
                Case DBT_DEVICEARRIVAL

                    Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)

                    If DevType = DBT_DEVTYP_VOLUME Then

                        Dim Vol As New DEV_BROADCAST_VOLUME

                        Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))

                        If Vol.Dbcv_Flags = 0 Then

                            For i As Integer = 0 To 20

                                If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then

                                    Dim Usb As String = Chr(65 + i) + ":\"

                                    MsgBox("Looks like a USB device was plugged in!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)

                                    Exit For

                                End If

                            Next

                        End If

                    End If
                    '
                    'Check if the message was for the removal of a device.
                Case DBT_DEVICEREMOVECOMPLETE

                    Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)

                    If DevType = DBT_DEVTYP_VOLUME Then

                        Dim Vol As New DEV_BROADCAST_VOLUME

                        Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))

                        If Vol.Dbcv_Flags = 0 Then

                            For i As Integer = 0 To 20

                                If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then

                                    Dim Usb As String = Chr(65 + i) + ":\"

                                    MsgBox("Looks like a volume device was removed!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)

                                    Exit For

                                End If

                            Next

                        End If

                    End If

            End Select

        End If

        MyBase.WndProc(M)

    End Sub

Your application should now be able to detect when a USB disk volume or drive has been inserted, changed, removed, etc.. Hopefully this may help someone. Have Fun!

Jason

25 thoughts on “Detect when Removable USB Volume Drive Devices are Attached or Removed – VB.NET

  1. Jason Post author

    Just copy and paste the structure and constants to your project. And then copy and paste the entire WndProc sub to your project. Then then while your program is running if it detects a removable item being connected or disconnected then it will throw a messagebox with a message about the device.

    Reply
  2. e-junior

    I’m sorry, can u tech me how to insert that code step by step? i’m newbie here… and sorry for my bad english..Thanks

    Reply
  3. michaelb958

    In case “Marshal.Something” isn’t working for you, just call it by full name: “System.Runtime.InteropServices.Marshal.Something”.

    Reply
  4. Hedi Guizani

    Maybe an easier code

    Private Const WM_DEVICECHANGE As Integer = &H219
    Private Const DBT_DEVICEARRIVAL As Integer = &H8000
    Private Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004
    ‘Private Const DBT_DEVTYP_VOLUME As Integer = &H2 ‘

    Public Sub RefreshUSB()
    Me.ds.drv_usb.Clear()
    Dim allDrives As List(Of IO.DriveInfo) = (From q In IO.DriveInfo.GetDrives() Where q.IsReady AndAlso q.DriveType = DriveType.Removable).ToList

    For Each d In allDrives
    If d.IsReady = True AndAlso d.DriveType = IO.DriveType.Removable Then
    Dim nr As UsbDs.drv_usbRow = Me.ds.drv_usb.Newdrv_usbRow
    nr.d_letter = d.Name.Replace(“\”, “”)
    nr.d_label = d.VolumeLabel
    nr.d_space = String.Format(“{0:f2} GB”, d.AvailableFreeSpace / Math.Pow(1024, 3))
    nr.d_free = String.Format(“{0:f2} GB”, d.AvailableFreeSpace / Math.Pow(1024, 3))
    Me.ds.drv_usb.Adddrv_usbRow(nr)
    End If
    Next
    End Sub

    Protected Overrides Sub WndProc(ByRef M As System.Windows.Forms.Message)
    On Error Resume Next
    If M.Msg = WM_DEVICECHANGE Then
    Select Case M.WParam
    Case DBT_DEVICEARRIVAL, DBT_DEVICEREMOVECOMPLETE
    Me.RefreshUSB()
    End Select
    End If
    MyBase.WndProc(M)
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.RefreshUSB()
    End Sub

    Reply
  5. Anonymous

    — how if the USB is write protected disk??i cant delete some of my files .. the ps says that my volume drive is invalid

    Reply
  6. NQuenault

    nr.d_space = String.Format(“{0:f2} GB”, d.AvailableFreeSpace / Math.Pow(1000, 3))
    nr.d_free = String.Format(“{0:f2} GB”, d.AvailableFreeSpace / Math.Pow(1000, 3))

    Or

    nr.d_space = String.Format(“{0:f2} GiB”, d.AvailableFreeSpace / Math.Pow(1024, 3))
    nr.d_free = String.Format(“{0:f2} GiB”, d.AvailableFreeSpace / Math.Pow(1024, 3))

    ….
    1024 -> Binary Prefix -> GiB (GibiBytes)
    1000 -> SE Prefix -> GB (GigaBytes)

    😉

    Reply
  7. Pratheesh

    what happens if the drive is u3..if so while connecting the 2 drives get connected separately but while removing the drives they get eject together, so the
    Vol.Dbcv_Unitmask = sum of the two ejected drives ie it need not be in the power of 2..if so how do you get the name of the removed drive

    Reply
  8. Pratheesh

    you can add the following code inside the “for loop” for device removal code

    If Math.Pow(2, i) Math.Pow(2, i 1) = Vol.Dbcv_Unitmask Then ‘—–>u3 drives
    Dim Usb As String = Chr(65 i) “:\”
    Dim usb1 As String = Chr(65 i 1) “:\”
    MsgBox(“Looks like a U3 was removed!” & vbNewLine & vbNewLine & “The drive letter is: ” & Usb.ToString & vbNewLine & vbNewLine & “The drive letter is: ” & usb1.ToString)
    Exit For
    End if

    this may work mostly

    Reply
  9. Octallon Urassa

    Thank so much for this code. it user full for my application but how can i remove usb devices by using vb.net 2008?

    Reply
  10. Jason Post author

    Hosein, that is pretty much what the code on this post does. It helps you to detect when a removable volume is inserted and/or detached. Unless your meaning something else?

    Jason

    Reply
  11. michael

    i appreciated this forum, but im a newbie in vb, can you help me to have a code that will detect my usb as drive F: and when remove it will trigger to task kill all programs that are present and will launch a lock screen asking for shutdown (small button) and if not press after 2 mins it will auto shutdown..please help me/… thanks

    Reply
  12. Jason Post author

    Hi, i’m not very familiar with Windows Presentation Foundation programming. But you can ask your question and if I can’t help maybe someone else will see your question and answer it for you.

    Reply

Leave a Reply