目次

キーボードのキーが押され続けている時間(秒数)を取得する - System.Windows.Input.Keyboardを利用 - C#

キーボードのキーが押され続けている時間(秒数)を取得するコードを紹介します。

UI

下図のUIを準備します。フォームにLabelを2つ配置します。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.Windows.Input;

namespace KeyState2
{
  public partial class FormMain : Form
  {
    bool LeftKeyPress = false;
    bool RightKeyPress = false;
    DateTime LeftKeyPressTime;
    DateTime RightKeyPressTime;

    public FormMain()
    {
      InitializeComponent();
    }

    private void FormMain_Load(object sender, EventArgs e)
    {
      Application.Idle += new EventHandler(Application_Idle);

    }

    private void Application_Idle(object sender, EventArgs e)
    {
      if (Keyboard.IsKeyDown(Key.Left) == true) {
        if (LeftKeyPress == true) {
          TimeSpan ts = DateTime.Now - LeftKeyPressTime;
          label1.Text = string.Format("左キーが押されています。{0:d}.{1:d}秒",
            ts.Seconds, ts.Milliseconds/100);
        }
        else {
          LeftKeyPressTime = DateTime.Now;
          LeftKeyPress = true;
          label1.Text = "左キーが押されています。";
        }
      }
      else {
        LeftKeyPress = false;
        label1.Text = "なし。";
      }

      if (Keyboard.IsKeyDown(Key.Right) == true) {
        if (RightKeyPress == true) {
          TimeSpan ts = DateTime.Now - RightKeyPressTime;
          label2.Text = string.Format("右キーが押されています。{0:d}.{1:d}秒",
            ts.Seconds, ts.Milliseconds / 100);
        }
        else {
          RightKeyPressTime = DateTime.Now;
          RightKeyPress = true;
          label2.Text = "右キーが押されています。";
        }
      }
      else {
        RightKeyPress = false;
        label2.Text = "なし。";
      }
    }

  }
}

解説

キーの押下検出についての説明はこちらの記事を参照して下さい。
if (Keyboard.IsKeyDown(Key.Left) == true) {
  if (LeftKeyPress == true) {
    TimeSpan ts = DateTime.Now - LeftKeyPressTime;
    label1.Text = string.Format("左キーが押されています。{0:d}.{1:d}秒",
      ts.Seconds, ts.Milliseconds/100);
  }
  else {
    LeftKeyPressTime = DateTime.Now;
    LeftKeyPress = true;
    label1.Text = "左キーが押されています。";
  }
}
else {
  LeftKeyPress = false;
  label1.Text = "なし。";
}
LeftKeyPress,RightKeyPressはキーが押されているかの状態を保存するbool型のフラグです。左キーが押されていることを検出できた場合、LeftKeyPressの値を確認し、キーが押され続けているのか、キーが押され始めたのかを判定します。キーが押され始めた(LeftKeyPress==false)の場合、LeftKeyPressTimeにキーが押された時点の時刻を設定し、LeftKeyPressをtrueに設定しキーが押されている状態に変えます。キーが押され続けている状態の場合は、変更はせず、現在時刻から左キーを押し始めた時刻(LeftkeyPressTime)を引きキーが押され続けている時間を求めラベルに表示します。
キーが押されていないことを検出できた場合は、LeftKeyPressの値をfalseに設定し、キーが押されていない状態に戻します。

実行結果

実行し、右カーソルキーを押します。キーが押された旨のメッセージが表示されキーが押されてからの時間が表示されます。


左右のキーを同時に押した場合はそれぞれのキーが押されている時間を画面に表示します。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-02-13
iPentec all rights reserverd.