How to check programatically if keyboard is connected or not?

狂风中的少年 提交于 2020-12-05 11:04:35

问题


I am developing an application with C# winforms.

Our application is going to be installed on win8 surface(touch screen device).

We want to check if a keyboard is connected via USB then our app will not show soft keypad otherwise it will show.

Many methods are avaliable to check for WinRT but none for winforms C#.

Please let me know if my question is not clear.

Thanks in advance.


回答1:


I just wrote this and tested on W8:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select Name from Win32_Keyboard");

        foreach(ManagementObject keyboard in searcher.Get())
        {
            if (!keyboard.GetPropertyValue("Name").Equals(""))
            {
                Console.WriteLine("KB Name: {0}", keyboard.GetPropertyValue("Name"));
            }
        }

I also connected a second keyboard and can see it detected. When I unplug one I get one entry, when unplug both I get nothing.

I also found some examples here: Example 1 and here Example 2

Hope this helps.




回答2:


To determine if it is connected via USB, check for that string:

private readonly string USB = "USB";

    private bool GetKeyboardPresent()
    {
        bool keyboardPresent = false;
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Keyboard");

        foreach (ManagementObject keyboard in searcher.Get())
        {
            foreach (PropertyData prop in keyboard.Properties)
            {
                if (Convert.ToString(prop.Value).Contains(USB))
                {
                    keyboardPresent = true;
                    break;
                }
            }      
        }

        return keyboardPresent;
    }

Or you could instead potentially use this Powershell command:

PS C:\Users\myUserID> Get-WmiObject Win32_Keyboard


来源:https://stackoverflow.com/questions/28471864/how-to-check-programatically-if-keyboard-is-connected-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!