LoginSignup
4
4

More than 5 years have passed since last update.

WindowsのC#でキーをリアルタイムに取得する方法

Last updated at Posted at 2015-06-17

イベントではなく、WINAPIを使用してキーを取得する方法です。
ゲームのメインループなどの中で使用します。

namespace Hoge
{
    public class Fuga
    {
        // DLLをインポートする必要がある
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern short GetKeyState(int nVirtKey);

        // キーの押しっぱなしを取得する
        public static bool IsKeyPress(System.Windows.Forms.Keys keyCode)
        {
            // GetKeyStateは最上位ビットが1か否かでキー投下の有無を取得できる
            return GetKeyState((int)keyCode) < 0;
        }
    }
}

注意点

GetKeyStateの戻り値はshort型(符号あり16bit)で、キー投下の判定は最上位ビットが立っているか否かで取得をする。
サイトによっては、戻り値をint型にしていたりキー投下判定が最下位ビットで行ったりしているため、注意が必要である。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4