sample code‎ > ‎

GetAsyncKeyState

・Input.h
#ifndef INPUT_H_
#define INPUT_H_

enum Operation {
  kNone,

  kUp,
  kDown,
  kLeft,
  kRight,

  kSelect,
  kCancel,

  kExit
};

// この関数はキーが押されるまで待つ
Operation GetOperation();
// この関数はすぐに制御を返す
Operation GetDownKey();

#endif  // INPUT_H_

・Input.cc
#include "Input.h"

#include <windows.h>

//引数でキーコードを指定し、そのキーが押されているなら true を返す
bool IsKeyDown(int key) {
  if (::GetAsyncKeyState(key) & 0x8000){
    return true;
  }
  return false;
}
//引数でキーコードを指定し、そのいずれかのキーが押されているなら true を返す
bool IsKeyDown (int key1 , int key2)
{
  if (IsKeyDown (key1) ||
      IsKeyDown (key2) ){
    return true;
  }
  return false;
}


Operation GetDownKey() {
  if(IsKeyDown('D', VK_RIGHT)) return kRight;//右
  if(IsKeyDown('S', VK_LEFT))  return kLeft;//左
  if(IsKeyDown('X', VK_DOWN))  return kDown;//下
  if(IsKeyDown('E', VK_UP))    return kUp;//上
  
  if(IsKeyDown('Y'))           return kSelect;
  if(IsKeyDown('N'))           return kCancel;

  if(IsKeyDown('Q'))           return kExit;

  return kNone;
}

Operation GetOperation() {
  static Operation before = kNone;

  for (;;) {
    Operation ret = GetDownKey();

    if(ret == kNone) {
      before = kNone;
    }else{
      if(ret !=  before) {
        return before = ret;
      }
    }
    ::Sleep(1);
  }
}

・main.cc
#include "Input.h"
#include <iostream>

int main(void)
{
  Operation ope;
  do {
    ope = GetOperation();
    std::cout << ope << std::endl;
  } while(ope != kExit);

  return 0;
}