简体   繁体   中英

Windows keyboard input c++

I know for linux you can get the keyboard input by reading from /dev/input/eventX. Is there a similar way to get input in Windows? Like knowing when a key is pressed without any 3rd party library

You can call GetAsyncKeyState , and check the bit 0x8000 in the return value:

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

int main() {
  while (1) {
    if (GetAsyncKeyState('A') & 0x8000) {
      std::cout << "'A' key is pressed\n";
    } else {
      std::cout << "'A' key is not pressed\n";
    }
    Sleep(250);
  }
}

You can find the list of virtual key codes here . Letters and numbers are represented by their regular corresponding (upper-case) ASCII-characters, so in this example it is just 'A' for the A key. But if you'd wanted to check the F1 key for example, you'd use VK_F1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM