Results 1 to 22 of 22

Thread: Detect when a USB mass storage device is plugged in.

  1. #1

    Thread Starter
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Arrow Detect when a USB mass storage device is plugged in.

    If you need to detect when a USB Mass Storage Device is plugged in to the system use the below code.

    (I have to give some credit to obi1kenobi for tweaking this code)

    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
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  2. #2
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: Detect when a USB mass storage device is plugged in.

    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.

    What's Wrong !!??

  3. #3
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Detect when a USB mass storage device is plugged in.

    Add a reference to System.Management (.NET tab).

  4. #4
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: Detect when a USB mass storage device is plugged in.

    hmm !!!

    thank you MattP

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

    Re: Detect when a USB mass storage device is plugged in.

    I made a very similar thing a while ago using APIs instead of WMI, if anyone finds that they cant use the WMI version .netninja has posted for some reason then maybe my old post could be useful: http://www.vbforums.com/showthread.php?t=534956
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

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


  6. #6
    Member
    Join Date
    Apr 2007
    Posts
    44

    Re: Detect when a USB mass storage device is plugged in.

    how to show in a textbox the usb drive letter ??
    Last edited by Biggy-D; Dec 23rd, 2008 at 04:44 PM.

  7. #7

    Thread Starter
    Hyperactive Member .NetNinja's Avatar
    Join Date
    Oct 2008
    Location
    USA
    Posts
    281

    Re: Detect when a USB mass storage device is plugged in.

    Look at the var USBDriveLetter....

    It holds the Drive Letter.
    "Don't try to be a great man. Just be a man and let history make its own judgement."

  8. #8
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: Detect when a USB mass storage device is plugged in.

    Hey thanks for the credit! Happy New Year!
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  9. #9
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: Detect when a USB mass storage device is plugged in.

    @Biggy-D and everyone trying to use this class:
    The events are raised on a thread different than the application's main (UI) thread. This means that if you want to modify any controls in the event handlers, you have to invoke the method on the UI thread instead of doing it directly. Not doing so will not result in an exception, however it will not produce the desired result.

    If you need help with invoking the controls, this tutorial written by jmcilhinney will be more than able to instruct you in the ways of the Force
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

  10. #10
    New Member
    Join Date
    Jun 2010
    Posts
    1

    Re: Detect when a USB mass storage device is plugged in.

    Hey thanks for the code .

    i have coded in new form But need your help as its not showing device attached to my pc.

    how can i detect ANY USB device plugged in?

  11. #11
    Frenzied Member
    Join Date
    Oct 2000
    Posts
    1,463

    Question Re: Detect when a USB mass storage device is plugged in.

    Does this work for most any USB memory sticks? Or just something like a USB hard drive? I'm anxious to try it when I get home today!!

    Thanks

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

    Re: Detect when a USB mass storage device is plugged in.

    Quote Originally Posted by WarrenW View Post
    Does this work for most any USB memory sticks? Or just something like a USB hard drive? I'm anxious to try it when I get home today!!

    Thanks
    I know my code that uses Windows APIs rather than WMI (here: http://cjwdev.wordpress.com/2009/11/...-drive-letter/) works for any USB drive so I assume this method using WMI does as well
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

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


  13. #13
    Frenzied Member
    Join Date
    Oct 2000
    Posts
    1,463

    Re: Detect when a USB mass storage device is plugged in.

    Thanks for the info. I just looked at the codre on your site which I will give a try also. I think I remember reading somewhere that not all systems will support WMI or can have a problem. Not sure how true that is. But api calls should always work fine. Just curious, why are you looking for the test.txt file when connected? Is that just a test to show what you can do?

    Thanks

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

    Re: Detect when a USB mass storage device is plugged in.

    Quote Originally Posted by WarrenW View Post
    Thanks for the info. I just looked at the codre on your site which I will give a try also. I think I remember reading somewhere that not all systems will support WMI or can have a problem. Not sure how true that is. But api calls should always work fine.
    Yep I prefer not to use WMI where ever possible because of precisely that reason. Admittedly WMI does work perfectly fine on the vast majority of machines but I've seen more than one case where it has not, so I use API's instead because they are pretty much guaranteed to work on any system.

    Quote Originally Posted by WarrenW View Post
    Just curious, why are you looking for the test.txt file when connected? Is that just a test to show what you can do?
    Yeah exactly - I think when I originally wrote the code it was to help someone who wanted to detect a USB drive when it was plugged in and then check to see if a specific file existed on it (hence the need to know which drive letter it had been assigned)
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

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


  15. #15
    Frenzied Member
    Join Date
    Oct 2000
    Posts
    1,463

    Question Re: Detect when a USB mass storage device is plugged in.

    Can this code or Chris's code be used in a Windows service? I tried creating one in VS2008 and putting the code in there but get alot of errors.

    Thanks

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

    Re: Detect when a USB mass storage device is plugged in.

    Quote Originally Posted by WarrenW View Post
    Can this code or Chris's code be used in a Windows service? I tried creating one in VS2008 and putting the code in there but get alot of errors.

    Thanks
    I know mine almost certainly cant because it relies on the message that Windows sends to all top level windows when a device is plugged in - and with a Service not having any windows (well, it should have anyway) that means it cannot receive the message.
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

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


  17. #17
    Frenzied Member
    Join Date
    Oct 2000
    Posts
    1,463

    Question Re: Detect when a USB mass storage device is plugged in.

    Chris,

    I put your code in a winform app in VS2008 and worked great! Is there any way to detect when it is removed/unplugged from the computer? I'm sure it can detect changes but to determine the same drive was removed.

    Thanks!

    Warren

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

    Re: Detect when a USB mass storage device is plugged in.

    Yeah it can definitely detect the device being removed but not 100% sure if you can get the drive letter that was removed - I imagine you can. I'll have a look tonight and see if I can put together an example.
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

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


  19. #19
    Member
    Join Date
    May 2010
    Location
    Abu Dhabi
    Posts
    60

    Re: Detect when a USB mass storage device is plugged in.

    ThankX for the codes... It works grate..

  20. #20
    Lively Member sameer spitfire's Avatar
    Join Date
    Nov 2001
    Location
    India
    Posts
    120

    Re: Detect when a USB mass storage device is plugged in.

    Good Show Thanx
    with Regards
    sameer Mulgaonkar

  21. #21
    New Member
    Join Date
    Feb 2011
    Posts
    2

    Re: Detect when a USB mass storage device is plugged in.

    HI Chris,
    I am developing a window mobile application, and I want to check if USB is connected or not, I tried to paste your code but it has few errors while compiling, I am not sure if this not meant to use for mobile apps. This is my first mobile application, so I am not very much sure about this. Can you please advice, my requirement is simple that I need to check if device is connected or not.

    Thanks
    Samar

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

    Re: Detect when a USB mass storage device is plugged in.

    I've no idea about the WMI method that someone else mentioned but I would be surprised if the API method I provided works on mobile platforms
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

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


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