英語で読む

次の方法で共有


フォームでキーボード入力メッセージを処理する方法 (Windows フォーム .NET)

Windows フォームは、メッセージがコントロールに到達する前に、フォーム レベルでキーボード メッセージを処理する機能を提供します。 この記事では、このタスクを実行する方法について説明します。

キーボード メッセージを処理する

アクティブフォームの KeyPress または KeyDown イベントを処理し、フォームの KeyPreview プロパティを trueに設定します。 このプロパティを使うと、キーボードは、フォーム上のコントロールに到達する前に、フォームによって受け取られます。 次のコード例では、すべての数値キーを検出し、147を使用して、KeyPress イベントを処理します。

C#
// Detect all numeric characters at the form level and consume 1,4, and 7.
// Form.KeyPreview must be set to true for this event handler to be called.
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= 48 && e.KeyChar <= 57)
    {
        MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed.");

        switch (e.KeyChar)
        {
            case (char)49:
            case (char)52:
            case (char)55:
                MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed.");
                e.Handled = true;
                break;
        }
    }
}

関連項目