How can I detect whether a keyboard is attached to the computer?

Raymond Chen

Today’s Little Program tells you whether a keyboard is attached to the computer. The short answer is “Enumerate the raw input devices and see if any of them is a keyboard.”

Remember: Little Programs don’t worry about silly things like race conditions.

#include <windows.h>
#include <iostream>
#include <vector>
#include <algorithm>

bool IsKeyboardPresent()
{
 UINT numDevices = 0;
  if (GetRawInputDeviceList(nullptr, &numDevices,
                            sizeof(RAWINPUTDEVICELIST)) != 0) {
   throw GetLastError();
 }

 std::vector<RAWINPUTDEVICELIST> devices(numDevices);

 if (GetRawInputDeviceList(&devices[0], &numDevices,
                           sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) {
  throw GetLastError();
 }

 return std::find_if(devices.begin(), devices.end(),
    [](RAWINPUTDEVICELIST& device)
    { return device.dwType == RIM_TYPEKEYBOARD; }) != devices.end();
}

int __cdecl main(int, char**)
{
 std::cout << IsKeyboardPresent() << std::endl;
 return 0;
}

There is a race condition in this code if the number of devices changes between the two calls to Get­Raw­Input­Device­List. I will leave you to fix it before incorporating this code into your program.

0 comments

Discussion is closed.

Feedback usabilla icon