Quantcast
Viewing all articles
Browse latest Browse all 3085

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.

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 3085

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>