我想知道检测鼠标或键盘是否插入计算机的最佳方法是什么?我有一个应用程序,主要用于单独的触摸屏,但我想知道是否有一个键盘插入不要拉起Windows键盘或包含数字键盘的表格。如果插入鼠标,则更改一些行为,如果不是。
答案 0 :(得分:2)
使用VB.Net,我会使用System.Management
(不要忘记在项目[菜单] - >添加参考中添加此引用)ManagementObjectSearcher
结合{{1}找到像这样的解决方案,
System.Linq
结果
您也可以对其进行硬编码以避免像TRiNE建议的输入错误(尽管使用C#)
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
并像这样打电话给他们
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
他们将产生相同的结果
答案 1 :(得分:1)
您可以使用C#System.Management
和ManagementObjectSearcher
以下是示例代码。根据您的需要进行修改。
public bool isPointingDeviceAttached()
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PointingDevice");
int devCount = 0;
foreach (ManagementObject obj in searcher.Get()) {
if(obj["Status"].ToString().Contains("OK")) // if device is ready
devCount++;
}
return devCount>0;
}
public bool isKeyboardAttached()
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Keyboard");
int devCount = 0;
foreach (ManagementObject obj in searcher.Get()) {
if (obj["Status"].ToString().Contains("OK")) // if device is ready
devCount++;
}
return devCount>0;
}
确保添加using System.Management;
行并在引用中添加System.Management
。
您可以使用更多ManagementObject属性来满足您的需要。这是一个属性列表和一些其他外部引用。