tags:

views:

51

answers:

2

I know you can do it with an WMI event or overriding WndProc and looking for the right messages, but i was wondering if there wasn't something hidden in the net framework that makes this task easyer.

+1  A: 

This free DriveDetector class provides this functionality (as least for USB drives, which is what I used it for). It uses the WndProc approach you describe.

I'm not aware of anything similar that is part of the standard .NET libraries.

dommer
A: 

In the following code, moDiskDetector will raise an EventArrived event when a new drive is detected.

To detect removal of a drive use "__InstanceDeletionEvent".

Private WithEvents moDiskAddWatcher As ManagementEventWatcher

Private Sub StartWatcher()

    If moDiskAddWatcher Is Nothing Then
        moDiskAddWatcher = CreateWatcher("__InstanceCreationEvent", "(TargetInstance ISA 'Win32_DiskDrive')")
    End If
    moDiskAddWatcher.Start()

End Sub

Private Sub StopWatcher()

    If moDiskAddWatcher IsNot Nothing Then
        moDiskAddWatcher.Stop()
        moDiskAddWatcher.Dispose()
    End If

End Sub

Private Function CreateWatcher(ByVal sClassName As String, ByVal sCondition As String) As ManagementEventWatcher

    Dim oQuery As New WqlEventQuery()

    oQuery.EventClassName = sClassName
    oQuery.WithinInterval = New TimeSpan(0, 0, 5)
    oQuery.Condition = sCondition
    Return New ManagementEventWatcher(oQuery)

End Function
MattH