Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check programatically if keyboard is connected or not?

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.

like image 221
2intor Avatar asked Feb 12 '15 07:02

2intor


2 Answers

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.

like image 106
callmebob Avatar answered Nov 12 '22 01:11

callmebob


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
like image 27
user8128167 Avatar answered Nov 12 '22 02:11

user8128167