Page 1 of 2 12 LastLast
Results 1 to 40 of 58

Thread: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

  1. #1

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    I'm looking for a way to detect when a new USB mass storage device is inserted in one of the pc's USB ports... I need to get it's drive letter and check for the existence of a particular file. Any ideas?
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  2. #2

  3. #3
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Here is a VERY lame way to do it. Just put this in a Timer_Tick function:

    Code:
               Dim oDrive As DriveInfo
                For Each oDrive In DriveInfo.GetDrives
                    If oDrive.DriveType = IO.DriveType.Removable Then
                        MessageBox.Show("Removable USB Drive " & oDrive.Name & " found.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification, False)
                        Exit Sub
                    End If
                Next
    You can also use WMI like this (This is the entire form class):

    Code:
    Imports System.Management
    
    Public Class Form1
        Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
        Public USBDriveName As String
        Public USBDriveLetter As String
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            StartDetection()
        End Sub
    
        Public Sub StartDetection()
            Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'")
    
            m_MediaConnectWatcher = New ManagementEventWatcher
            m_MediaConnectWatcher.Query = 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 As ManagementBaseObject
            Dim obj As ManagementBaseObject
    
            mbo = CType(e.NewEvent, ManagementBaseObject)
            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")
                    End If
                Case "__InstanceDeletionEvent"
                    If obj("InterfaceType") = "USB" Then
                        MsgBox(GetDriveLetterFromDisk(obj("Name")))
                        If obj("Caption") = USBDriveName Then
                            USBDriveLetter = ""
                            USBDriveName = ""
                        End If
                    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 = ""
    
            Name = Replace(Name, "\", "\\")
    
            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
    
    End Class
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  4. #4

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Thanks to both of you. I'll try out the code as soon as I can and post accordingly.
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  5. #5

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Ok after adding references to System.Management and System.Management.Instrumentation, I made some changes to the code, in order to fix several errors (concatenation operator cannot be used on Object etc.)

    Code:
    Imports System.Management
    
    Public Class Form3
        Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
        Public USBDriveName As String
        Public USBDriveLetter As String
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            StartDetection()
        End Sub
    
        Private Sub Form3_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
            m_MediaConnectWatcher.Stop()
            m_MediaConnectWatcher.Dispose()
        End Sub
    
        Public Sub StartDetection()
            Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'")
    
            m_MediaConnectWatcher = New ManagementEventWatcher
            m_MediaConnectWatcher.Query = 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 As ManagementBaseObject
            Dim obj As ManagementBaseObject
    
            mbo = CType(e.NewEvent, ManagementBaseObject)
            obj = CType(mbo("TargetInstance"), ManagementBaseObject)
    
            Select Case mbo.ClassPath.ClassName
                Case "__InstanceCreationEvent"
                    If obj.Item("InterfaceType").ToString = "USB" Then
                        USBDriveName = obj.Item("Caption").ToString
                        USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString)
                        MessageBox.Show(USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
                    End If
                Case "__InstanceDeletionEvent"
                    If obj.Item("InterfaceType").ToString = "USB" Then
                        MessageBox.Show(USBDriveName & " was disconnected. " & USBDriveLetter & " is now inaccessible.") 'GetDriveLetterFromDisk(obj.Item("Name").ToString))
                        If obj.Item("Caption").ToString = USBDriveName Then
                            USBDriveLetter = ""
                            USBDriveName = ""
                        End If
                    End If
                Case Else
                    MessageBox.Show("nope: " & obj.Item("Caption").ToString)
            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 = ""
    
            Name = Replace(Name, "\", "\\")
    
            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.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
                mos_disk = New ManagementObjectSearcher(oq_disk)
                For Each obj_disk In mos_disk.Get()
                    ans &= obj_disk.Item("Name").ToString & ","
                Next
            Next
    
            Return ans.Trim(","c)
        End Function
    Please note that the ManagementEventWatcher must be disposed of when the form is closed, otherwise an exception is thrown.
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  6. #6

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    One more question... Would this same code also detect the insertion of a memory card in a card reader? If not, would it be possible to make some changes so that it does?
    Last edited by obi1kenobi; Dec 2nd, 2008 at 06:55 PM.
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  7. #7
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    I'm not 100% sure if it would. It would probably depend on the reader. I would guess it would if the reader was USB external, but for internal readers maybe/maybe not.
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  8. #8
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Quote Originally Posted by .NetNinja
    I'm not 100% sure if it would. It would probably depend on the reader. I would guess it would if the reader was USB external, but for internal readers maybe/maybe not.
    Just to let you guys know, both internal and external usb readers hook to the system's usb bus, meaning internal readers are hooked to the usb hub built into the motherboard/usb expansion card on the system.
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  9. #9
    PowerPoster Jenner's Avatar
    Join Date
    Jan 2008
    Location
    Mentor, OH
    Posts
    3,712

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    There are some chip readers that have a permanent "drive assignment" in Windows (just like a CDROM does, whether it has a disk in it or not) and they don't recognize the act of chip insertion or removal. Those may cause problems.
    My CodeBank Submissions: TETRIS using VB.NET2010 and XNA4.0, Strong Encryption Class, Hardware ID Information Class, Generic .NET Data Provider Class, Lambda Function Example, Lat/Long to UTM Conversion Class, Audio Class using BASS.DLL

    Remember to RATE the people who helped you and mark your forum RESOLVED when you're done!

    "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe. "
    - Albert Einstein

  10. #10
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Quote Originally Posted by Jenner
    There are some chip readers that have a permanent "drive assignment" in Windows (just like a CDROM does, whether it has a disk in it or not) and they don't recognize the act of chip insertion or removal. Those may cause problems.
    Both of my card readers (one internal and one external that plugs into a usb port on the usb hub in my dell monitor) both have an assigned windows drive letter (Once the external one's plugged windows assigns it the drive letters) for each reader (4 each) and when I insert my sd card windows xp some how detects it and pops up the 'What do you want to do with it" window immediately after insertion of the card.

    Windows Vista pops up with the same window 5 minutes after the card's inserted. Then again Vista wasn't built to get work done, so 5 minute delays are excusable to the public.
    Last edited by JuggaloBrotha; Dec 4th, 2008 at 09:04 AM.
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  11. #11

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Well my card reader doesn't have a permanent drive assignment, so is it safe to assume that the code will work as is? I do not own a card so I cannot try it myself... :/
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  12. #12
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    I am not sure I would say it is safe to assume. I am fairly certain that is the case though.
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  13. #13
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    If the above code is working, perhaps a codebank thread would be in order?
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  14. #14
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    515

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    This is a great thread. Subscribing.

  15. #15

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Sorry for being absent for so long a period, I had no access to the internet for over 10 days :S

    The code works like a charm, no issues as of this moment. Since I didn't provide the code in the first place, I only tweaked it to work better, I believe it would be more appropriate if .NetNinja posted this in the CodeBank... After all, I don't want to take credit for something someone else did...
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  16. #16
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Thumbs up Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Quote Originally Posted by obi1kenobi
    Sorry for being absent for so long a period, I had no access to the internet for over 10 days :S

    The code works like a charm, no issues as of this moment. Since I didn't provide the code in the first place, I only tweaked it to work better, I believe it would be more appropriate if .NetNinja posted this in the CodeBank... After all, I don't want to take credit for something someone else did...
    I have added this to the code bank: http://www.vbforums.com/showthread.php?t=550730

    obi1kenobi: Thanks again for the tweak.
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  17. #17
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Code:
    Error	1	Type 'ManagementEventWatcher' is not defined.	
    Error	2	Type 'WqlEventQuery' is not defined.	
    Error	3	Type 'ManagementEventWatcher' is not defined.	
    Error	4	Type 'System.Management.EventArrivedEventArgs' is not defined.	
    Error	5	Type 'ManagementBaseObject' is not defined.	
    Error	6	Type 'ManagementBaseObject' is not defined.	
    Error	7	Type 'ManagementBaseObject' is not defined.	
    Error	8	Type 'ManagementBaseObject' is not defined.	
    Error	9	Type 'ObjectQuery' is not defined.	
    Error	10	Type 'ManagementObjectSearcher' is not defined.	
    Error	11	Type 'ManagementObject' is not defined.	
    Error	12	Type 'ObjectQuery' is not defined.	
    Error	13	Type 'ManagementObjectSearcher' is not defined.

  18. #18
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Did you import System.Management?
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  19. #19
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    how to remove msgbox and show result in TextBox ?

  20. #20

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Remove the "MessageBox.Show" part and replace it with "TextBox1.Text =" - no quotation marks.
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  21. #21
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    obi1kenobi thnx for reply

    i try but doesn't work, did nothing !!
    any idea !

  22. #22

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Perhaps the name of the TextBox you are using is different? I can't think of another reason which would prevent it from working. Post your code and I'll fix it for you.
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  23. #23
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Code:
    Imports System.Management
    Public Class Form1
        Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
        Public USBDriveName As String
        Public USBDriveLetter As String
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            StartDetection()
        End Sub
        Public Sub StartDetection()
            Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'")
    
            m_MediaConnectWatcher = New ManagementEventWatcher
            m_MediaConnectWatcher.Query = 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 As ManagementBaseObject
            Dim obj As ManagementBaseObject
    
            mbo = CType(e.NewEvent, ManagementBaseObject)
            obj = CType(mbo("TargetInstance"), ManagementBaseObject)
    
            Select mbo.ClassPath.ClassName
                Case "__InstanceCreationEvent"
                    If obj.Item("InterfaceType").ToString = "USB" Then
                        USBDriveName = obj.Item("Caption").ToString
                        USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString)
                        TextBox1.Text = (USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
                    End If
                Case "__InstanceDeletionEvent"
                    If obj.Item("InterfaceType").ToString = "USB" Then
                        TextBox1.Text = (USBDriveName & " was disconnected. " & USBDriveLetter & " is now inaccessible.") 'GetDriveLetterFromDisk(obj.Item("Name").ToString))
                        If obj.Item("Caption").ToString = USBDriveName Then
                            USBDriveLetter = ""
                            USBDriveName = ""
                        End If
                    End If
                Case Else
                    TextBox1.Text = ("nope: " & obj.Item("Caption").ToString)
            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 = ""
    
            Name = Replace(Name, "\", "\\")
    
            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.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
                mos_disk = New ManagementObjectSearcher(oq_disk)
                For Each obj_disk In mos_disk.Get()
                    ans &= obj_disk.Item("Name").ToString & ","
                Next
            Next
    
            Return ans.Trim(","c)
        End Function
    End Class
    doesn't work for me !!!!

  24. #24
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Why do you have :
    Code:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
     Handles MyBase.Load
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  25. #25

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    @.NetNinja: That's the correct event signature, check your IDE.

    @Biggy-D: The code you are using is ok. Add the reference to System.Management and it'll work fine. Right-click your project in solution explorer, click Properties, select the References tab, then click Add and in the .Net tab scroll to System.Management and select it. The errors will disappear.
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  26. #26
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    @obi1kenobi

    the reference :System.Management is already inserted ..
    the code doesn't give errors,but doesn't work when i change " messagebox to textbox.text " in the textbox.text i want to display drive info, like messagebox info.

  27. #27

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    I tried it in 2005 and it indeed didn't work, I got an InvalidCOMException. I'm puzzled, it should have worked XC
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  28. #28
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    What did you try that did not work?
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  29. #29
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    i have 2008 !!

  30. #30
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    What did you mean by it doesn't work? It doesn't detect or are you encountering some exceptions?
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  31. #31
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    ok. i try to change
    Code:
    MessageBox.Show(USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
    to
    Code:
    TextBox1.text = (USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
    in textbox1 doesn't show result..
    Last edited by Biggy-D; Jan 8th, 2009 at 11:21 AM.

  32. #32
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    When using the MessageBox does it get the correct result?
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  33. #33
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    when using the messagebox i get the correct result..

  34. #34
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    That's odd. Care to post the relevant section of the code where you are using a textbox?
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  35. #35
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    textbox1 is in a form1, my code is under form1 class .
    here is my code :

    vb Code:
    1. Imports System.Management
    2. Public Class Form1
    3.     Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
    4.     Public USBDriveName As String
    5.     Public USBDriveLetter As String
    6.  
    7.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    8.         StartDetection()
    9.     End Sub
    10.     Public Sub StartDetection()
    11.         Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'")
    12.  
    13.         m_MediaConnectWatcher = New ManagementEventWatcher
    14.         m_MediaConnectWatcher.Query = query2
    15.         m_MediaConnectWatcher.Start()
    16.     End Sub
    17.     Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived
    18.         Dim mbo As ManagementBaseObject
    19.         Dim obj As ManagementBaseObject
    20.  
    21.         mbo = CType(e.NewEvent, ManagementBaseObject)
    22.         obj = CType(mbo("TargetInstance"), ManagementBaseObject)
    23.  
    24.         Select mbo.ClassPath.ClassName
    25.             Case "__InstanceCreationEvent"
    26.                 If obj.Item("InterfaceType").ToString = "USB" Then
    27.                     USBDriveName = obj.Item("Caption").ToString
    28.                     USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString)
    29.                     TextBox1.Text = (USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
    30.                 End If
    31.             Case "__InstanceDeletionEvent"
    32.                 If obj.Item("InterfaceType").ToString = "USB" Then
    33.                     TextBox1.Text = (USBDriveName & " was disconnected. " & USBDriveLetter & " is now inaccessible.") 'GetDriveLetterFromDisk(obj.Item("Name").ToString))
    34.                     If obj.Item("Caption").ToString = USBDriveName Then
    35.                         USBDriveLetter = ""
    36.                         USBDriveName = ""
    37.                     End If
    38.                 End If
    39.             Case Else
    40.                 TextBox1.Text = ("nope: " & obj.Item("Caption").ToString)
    41.         End Select
    42.     End Sub
    43.     Private Function GetDriveLetterFromDisk(ByVal Name As String) As String
    44.         Dim oq_part, oq_disk As ObjectQuery
    45.         Dim mos_part, mos_disk As ManagementObjectSearcher
    46.         Dim obj_part, obj_disk As ManagementObject
    47.         Dim ans As String = ""
    48.  
    49.         Name = Replace(Name, "\", "\\")
    50.  
    51.         oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition")
    52.         mos_part = New ManagementObjectSearcher(oq_part)
    53.         For Each obj_part In mos_part.Get()
    54.  
    55.             oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
    56.             mos_disk = New ManagementObjectSearcher(oq_disk)
    57.             For Each obj_disk In mos_disk.Get()
    58.                 ans &= obj_disk.Item("Name").ToString & ","
    59.             Next
    60.         Next
    61.  
    62.         Return ans.Trim(","c)
    63.     End Function
    64. End Class

  36. #36
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    Could it have something to do with Cross Threading? (I could be way off)
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  37. #37

    Thread Starter
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    I tried his code in 2005 and it just ignored the TextBox1.Text line and then threw the exception I described... I can't make heads or tails of this problem...
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  38. #38
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    It could be a problem with WMI, when I have time I will try to dig furhter into it.
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  39. #39
    Pro Grammar chris128's Avatar
    Join Date
    Jun 2007
    Location
    England
    Posts
    7,604

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    I know I already pointed this out in the codebank entry but it may just be worth mentioning here if you guys are having problems with the WMI version : I made something that does pretty much the exact same thing obi1 described in his original post (ie detect when a new drive is inserted and check for a file on it) using Windows API.
    Read all 7 posts in this thread (The 2nd post provides the full code but then I fixed a little problem with the drive letter assignment in the last post) and see if it helps: http://www.vbforums.com/showthread.php?t=534956

    Oh and the way I'm searching for the file in that 2nd post isnt great lol I dont know why I was using GetFiles instead of FileExists... it still works but it could be slow if the USB device has a lot of files on it so you might want to change that bit (in the WndProc sub)
    Last edited by chris128; Jan 10th, 2009 at 10:15 AM.
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

    Blog: cjwdev.wordpress.com
    Web: www.cjwdev.co.uk


  40. #40
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: [2008] Detect the insertion of a USB mass storage device (USB stick etc.)

    chris128

    the WMI version work for me !

    thnx

Page 1 of 2 12 LastLast

Posting Permissions

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



Click Here to Expand Forum to Full Width