-
Dec 17th, 2008, 07:41 AM
#1
Thread Starter
Hyperactive Member
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."
-
Dec 17th, 2008, 03:54 PM
#2
Member
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 !!??
-
Dec 17th, 2008, 05:02 PM
#3
Re: Detect when a USB mass storage device is plugged in.
Add a reference to System.Management (.NET tab).
-
Dec 18th, 2008, 06:13 AM
#4
Member
Re: Detect when a USB mass storage device is plugged in.
hmm !!!
thank you MattP
-
Dec 20th, 2008, 02:18 PM
#5
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
-
Dec 23rd, 2008, 08:38 AM
#6
Member
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.
-
Dec 29th, 2008, 10:46 AM
#7
Thread Starter
Hyperactive Member
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."
-
Dec 29th, 2008, 04:11 PM
#8
Frenzied Member
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
-
Jan 18th, 2009, 11:20 AM
#9
Frenzied Member
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
-
Jun 26th, 2010, 03:44 AM
#10
New Member
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?
-
Jul 2nd, 2010, 09:54 AM
#11
Frenzied Member
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
-
Jul 2nd, 2010, 10:36 AM
#12
Re: Detect when a USB mass storage device is plugged in.
Originally Posted by WarrenW
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
-
Jul 2nd, 2010, 10:39 AM
#13
Frenzied Member
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
-
Jul 2nd, 2010, 11:56 AM
#14
Re: Detect when a USB mass storage device is plugged in.
Originally Posted by WarrenW
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.
Originally Posted by WarrenW
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)
-
Jul 12th, 2010, 01:15 PM
#15
Frenzied Member
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
-
Jul 12th, 2010, 04:31 PM
#16
Re: Detect when a USB mass storage device is plugged in.
Originally Posted by WarrenW
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.
-
Jul 16th, 2010, 08:27 AM
#17
Frenzied Member
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
-
Jul 16th, 2010, 08:34 AM
#18
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.
-
Jul 20th, 2010, 06:32 AM
#19
Member
Re: Detect when a USB mass storage device is plugged in.
ThankX for the codes... It works grate..
-
Oct 25th, 2010, 03:38 AM
#20
Lively Member
Re: Detect when a USB mass storage device is plugged in.
with Regards
sameer Mulgaonkar
-
Feb 17th, 2011, 08:03 AM
#21
New Member
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
-
Feb 17th, 2011, 11:41 AM
#22
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|