Search code examples
c#keyboardportstatedetect

Detecting PS/2 port state in C#


I am attempting to simply detect whether there is a keyboard attached to the PS/2 port on my machine. The idea is that the computer will boot up, although if it detects a USB device or PS/2 keyboard, it reboots into an administrator mode.

I have handled the USB aspect, although I have had no luck in finding any documentation for the PS/2 port. Some posts have said it is not possible to detect a keyboard plugged into a PS/2 port after boot, although I simply wish to check whether there is one connected at boot time.

I am using C# for my program and therefore any solution in this language would be very helpful, although assistance in any language would be beneficial.


Solution

  • WMI seems to be doing it:

    ConnectionOptions opts = new ConnectionOptions();
    ManagementScope scope = new ManagementScope(@"\\.\root\cimv2", opts);
    string query = "select * from Win32_Keyboard";
    System.Management.ObjectQuery oQuery = new ObjectQuery(query);
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, oQuery);
    ManagementObjectCollection recordSet = searcher.Get();
    foreach (ManagementObject record in recordSet)
    {
        Console.WriteLine("" + record.Properties["Description"].Value);
        Console.WriteLine("" + record.Properties["Layout"].Value);
        Console.WriteLine("" + record.Properties["DeviceID"].Value);
        Console.WriteLine("" + record.Properties["PNPDeviceID"].Value);
        Console.WriteLine("" + record.Properties["Status"].Value + "\n");
    }
    

    returns:

    USB Human Interface Device
    0000040C
    USB\VID_03F0&PID_0024\6&1A939CC4&0&1
    USB\VID_03F0&PID_0024\6&1A939CC4&0&1
    OK
    
    Standard 101/102-Key or Microsoft Natural PS/2 Keyboard
    0000040C
    ACPI\PNP0303\4&3432CBB0&0
    ACPI\PNP0303\4&3432CBB0&0
    Error
    

    I don't have a PS/2 keyboard, so the status gives an error, but you should have an OK status if one is connected.