LoginSignup
2
2

More than 5 years have passed since last update.

C#のコンソールアプリで、特定のキーが押されているか調べる

Last updated at Posted at 2019-02-27

概要

C#のコンソールアプリケーションで、無限ループ中に特定のキーが押されたら終了処理をしてアプリケーションを終わる…という処理がしたかったが、ググっても、ググっても、ウインドウアプリでのやり方しか出てこなかったので、出来るようになった方法をポエムにまとめておく。

※コメント欄にて、もっと簡単な方法を教えて貰った。

前提

クラス宣言の直後にDLL読み込みを記述しておく。

class Program {
  [System.Runtime.InteropServices.DllImport("user32.dll")]
  private static extern short GetKeyState(int nVirtKey);
  ・
  ・
  ・

キー押下判断

while (GetKeyState(0x51) == 0) {
  // なにかしらの処理
}

これで、「Q」が押されるまでwhileループを廻り続ける。

2
2
1

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
2
2