フォームでキーボードのKeyDown,KeyUp,KeyPress イベントをすべて受け取る - C#

フォームでキーボードのキーイベント(KeyDown,KeyUp,KeyPress )をすべて受け取る方法を紹介します。

概要

フォームでキーボードのKeyDown,KeyUp,KeyPressをすべて受け取る場合は、フォームのKeyPreviewプロパティをTrueに設定します。

プログラム例

UI

下図のUIを作成します。

コード

下記のコードを記述します。チェックボックスのCheckedChangedイベントとフォームのKeyDownイベントを実行します。
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;

namespace FormKeyPreview
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
      this.KeyPreview = checkBox1.Checked;
    }

    private void FormMain_KeyDown(object sender, KeyEventArgs e)
    {
      textBox_OutPut.Text += e.KeyCode.ToString();
    }
  }
}

解説

チェックボックスのチェックが変更されるとフォームのKeyPreviewプロパティの値を変更します。
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
  this.KeyPreview = checkBox1.Checked;
}

フォームのKeyDownイベントで押されたキーを下部のテキストボックスに表示します。
private void FormMain_KeyDown(object sender, KeyEventArgs e)
{
  textBox_OutPut.Text += e.KeyCode.ToString();
}

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


上部のテキストボックスをクリックしフォーカスを移します。キーを押して文字を入力します。テキストボックスに文字は入力されますが、下部のテキストボックスには何も表示されません。


チェックボックスにチェックをし、上部のテキストボックスにキーを押して文字を入力します。下部のテキストボックスに押したキーのキーコードが表示されます。

KeyPreview = false の場合の動作

KeyPreviewがfalseの場合の動作を紹介します。

コード

先のUIを用いて以下のコードを記述します。textBox1のKeyuDownイベントを追加します。
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;

namespace FormKeyPreview
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
      this.KeyPreview = checkBox1.Checked;
    }

    private void FormMain_KeyDown(object sender, KeyEventArgs e)
    {
      textBox_OutPut.Text += e.KeyCode.ToString();

    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
      textBox_OutPut.Text += e.KeyCode.ToString();
    }
  }
}

解説

KeyPreviewのKeyDownイベントに加えtextBox1のKeyDownイベントも実装しました。KeyPreviewがfalseの場合の動作を確認します。

実行結果

プロジェクトを実行し、textBox1で文字を入力します。textBox1のKeyDownイベントが発生し下部のテキストボックスにキーコードの値が表示されます。


KeyPreviewのチェックを入れKeyPreviewがtrueの状態でtextBox1に文字を入力します。textBox1のKeyDownイベントとフォームのKeyDownイベントが発生するため、下部のテキストボックスにキーコードの値が2つずつ表示されます。


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