Jump to content

USB Drive Detector

- - - - -

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

#1
MXTECH

MXTECH

    Learning Programmer

  • Members
  • PipPipPip
  • 47 posts
hey alll i want to make my USB Virus remover app run as soon as a new USB is detected so to remove the threat of propergation from networks, the code is:

 ' USB DEVICE DETECTION BELOW:

    '========================================================================================================================


    Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher


    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



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


        Dim mbo, obj As ManagementBaseObject


        ' the first thing we have to do is figure out if this is a creation or deletion event

        mbo = CType(e.NewEvent, ManagementBaseObject)

        ' next we need a copy of the instance that was either created or deleted

        obj = CType(mbo("TargetInstance"), ManagementBaseObject)


        Select Case mbo.ClassPath.ClassName

            Case "__InstanceCreationEvent"

                If obj("InterfaceType") = "USB" Then

                    MsgBox(obj("Caption") & " (Drive letter " & GetDriveLetterFromDisk(obj("Name")) & ") has been plugged in")

                Else

                    MsgBox(obj("InterfaceType"))

                End If

            Case "__InstanceDeletionEvent"

                If obj("InterfaceType") = "USB" Then

                    MsgBox(obj("Caption") & " has been unplugged")

                    If obj("Caption") = USBDriveName Then

                        USBDriveLetter = ""

                        USBDriveName = ""

                    End If

                Else

                    MsgBox(obj("InterfaceType"))

                End If

            Case Else

                MsgBox("nope: " & obj("Caption"))

        End Select

    End Sub


    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
BUT Thats code doesnt work for me cos i run Visual Studio 2008 and it says:
1.ManagementBaseObject = unknown term
2.ManagementEventWatcher =unknown term

Any1 help????

#2
MXTECH

MXTECH

    Learning Programmer

  • Members
  • PipPipPip
  • 47 posts
Ok i been playing around with it and i have came to a block,
It DOES detect when a new usb is inserted or removed, BUT it doesnt tell me what drive letter so i can scan in as soon as it is in? help, here is the updated code:

Imports System.Management


Public Class Form1

    Private WithEvents EventWatcher As ManagementEventWatcher

    Private _Query As WqlEventQuery

    Private _Drive As String

    Private _Timeout As Integer = 10


    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        EventWatcher.Stop()

    End Sub


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

        StartWatcher()

    End Sub


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

        If CType(e.NewEvent, ManagementBaseObject)("__Class").ToString = "__InstanceCreationEvent" Then

            MsgBox("Device inserted.")

            scanusb()

        Else

            If CType(e.NewEvent, ManagementBaseObject)("__Class").ToString = "__InstanceDeletionEvent" Then

                MsgBox("Device removed.")

            End If


        End If

    End Sub


    Private Sub StartWatcher()

        _Query = New WqlEventQuery("select * from __InstanceOperationEvent within 1 where TargetInstance ISA 'Win32_LogicalDisk'")

        EventWatcher = New ManagementEventWatcher(_Query)

        EventWatcher.Start()

    End Sub



    Private Sub Get_Drive()

        Dim DriveFound As Boolean

        Dim BaseTime As DateTime = Now

        Dim Drives() As System.IO.DriveInfo


        Do Until DriveFound = True Or Now >= DateAdd(DateInterval.Second, _Timeout, BaseTime)

            Drives = System.IO.DriveInfo.GetDrives

            For Each Drive As System.IO.DriveInfo In Drives

                If Drive.IsReady Then

                    If Drive.VolumeLabel.ToLower = "awdatakey" Then

                        _Drive = Drive.Name

                        DriveFound = True

                    End If

                End If

            Next

        Loop

        If DriveFound = True Then

            MsgBox("Device " & _Drive & " inserted")

            Scanusb()

        End If

    End Sub

end class