Support Forums
Detect When New Media/Storage Device Insertted - Get It's Drive Letter - 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: Detect When New Media/Storage Device Insertted - Get It's Drive Letter (/showthread.php?tid=25538)



Detect When New Media/Storage Device Insertted - Get It's Drive Letter - AceInfinity - 03-08-2012

Here's a snippet I created today just by fooling around, but what this does is updates a list of loaded drives into a list and updates that for comparison to see what the new drive letter of a newly inserted device is through the WM_DEVICECHANGE windows messaging parameters.

The detection of the device will prompt you with a message box of the new mounted drive letter as soon as you insert a removable storage device.

If you need any help, or want to understand more about this just post in the thread below. More information will be available on my forum here: http://tech.reboot.pro

Code:
Imports System.IO

Public Class Form1

    Private DrivesList As List(Of String)

    Private WM_DEVICECHANGE As Integer = &H219
    Public Enum WM_DEVICECHANGE_WParams As Integer
        DeviceInserted = &H8000
        DeviceRemoved = &H8004
    End Enum

    Protected Overrides Sub WndProc(ByRef w As System.Windows.Forms.Message)

        If w.Msg = WM_DEVICECHANGE Then
            Select Case w.WParam
                Case WM_DEVICECHANGE_WParams.DeviceInserted
                    For Each Drive As DriveInfo In DriveInfo.GetDrives()
                        If Drive.IsReady AndAlso Not DrivesList.Contains(Drive.Name) Then
                            'Displays the new drive letter for the device
                            MsgBox(Drive.Name)
                        End If
                    Next
                Case WM_DEVICECHANGE_WParams.DeviceRemoved
                    DrivesList = New List(Of String)
                    For Each Drive As DriveInfo In DriveInfo.GetDrives()
                        If Drive.IsReady Then _
                        DrivesList.Add(Drive.Name)
                    Next
            End Select
        End If
        MyBase.WndProc(w)

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DrivesList = New List(Of String)

        For Each Drive As DriveInfo In DriveInfo.GetDrives()
            If Drive.IsReady Then _
            DrivesList.Add(Drive.Name)
        Next
    End Sub

End Class