July 20th, 2015

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

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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.