Question Detect when USB Mouse is Connected/Disconnect

AdamBray

New member
Joined
Oct 16, 2009
Messages
3
Programming Experience
1-3
Hi,

I'm fairly new to VB .NET, though I have a background in development (though it is rusty).

I'm writting a little application that needs to detect when a USB Mouse is Connected and Disconnected. I am running into a dead end when trying to determine the best way detect this. I have tried WMI and WmdProc but I think I am hitting a mental block trying to figure out the best option.

If anyone has any suggestions and sample code on the best way to listen for the connection and disconnection of a USB mouse, I would greatly appreciate the assistance!
 
FYI,

Here is the WmdProc code I used, but it seems to fire when I insert a CD - causing an exception:

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Dim MousePresent As Boolean
Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity")
Dim PnPDevice As ManagementObject

MousePresent = False

'Check to make sure that Autodetect is enabled
If btnToggle.Text = "Disable Autodetect" Then
'Was there a Device change recorded?
If m.Msg = WM_DEVICECHANGE Then
'Was there a Dev Node Change recorded
If m.WParam = WM_DEVICECHANGE_WPPARAMS.DBT_DEVNODES_CHANGED Then
...

Here is the WMI code I have tried and it doesn't even seem to fire :(

Public Sub StartDetection()
' __InstanceOperationEvent will trap both Creation and Deletion of class instances
Dim query2 As String = "SELECT * FROM __InstanceOperationEvent WHERE TargetInstance ISA ""Win32_DeviceChangeEvent"""
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") & " has been plugged in")
Else
MsgBox(obj("InterfaceType"))
End If
Case "__InstanceDeletionEvent"
If obj("InterfaceType") = "USB" Then
MsgBox(obj("Caption") & " has been unplugged")
Else
MsgBox(obj("InterfaceType"))
End If
Case Else
MsgBox("nope: " & obj("Caption"))
End Select
End Sub
End Class
 
Thanks Gir... I don't know if I'm blind or if the SysInfo control doesn't exist in Visual Studio 2008. Any ideas?
 
I am working with both vb6 and vb2005. vb2005 you need to go to add references, the COM tab. Then under that look for "Microsoft SysInfo control 6.0". vs2008 is probably the same way. (Don't currently have it to check, sorry.)
 
Back
Top