I was wanting to know what is the best way to detect if a mouse or keyboard is plugged in to the computer? I have an application that is mostly used in a touchscreen standalone but I want to know if there is a keyboard plugged in don't fire off pulling up the windows keyboard or a form that contains a numeric keypad. Then change some behavior if the mouse is plugged in against if it isn't.
Using VB.Net, I would use System.Management (don't forget to add this reference in the Project [Menu] -> Add Reference) ManagementObjectSearcher combined with System.Linq to find the solution like this,
Imports System
Imports System.Management
Imports System.Linq
Public Module Module1
Public Sub Main()
Console.WriteLine(HasDevice("PointingDevice"))
Console.WriteLine(HasDevice("Keyboard"))
Console.ReadKey()
End Sub
Public Function HasDevice(strtype As String)
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_" + strtype)
Dim result = From mobj In searcher.Get()
Select mobj Where mobj("Status").ToString() = 0
Return Not IsNothing(result)
End Function
End Module
Result

You could also hard-coded it to avoid input mistake like TRiNE suggested (though using C#)
Public Function HasPointingDevice()
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_PointingDevice")
Dim result = From mobj In searcher.Get()
Select mobj Where mobj("Status").ToString() = 0
Return Not IsNothing(result)
End Function
Public Function HasKeyboard()
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_Keyboard")
Dim result = From mobj In searcher.Get()
Select mobj Where mobj("Status").ToString() = 0
Return Not IsNothing(result)
End Function
And call them like this
Public Sub Main()
Console.WriteLine(HasPointingDevice())
Console.WriteLine(HasKeyboard())
Console.ReadKey()
End Sub
They will produce the same result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With