方法: キーボード入力を標準コントロールに変更する

Windows フォームは、キーボードの入力を使用して変更する機能を提供します。 キーの使用とは、メッセージ キューのさらに下のその他のメソッドとイベントが、キーの値を受信しないようにメソッドまたはイベント ハンドラー内のキーを処理することを表します。 キーの変更とは、メッセージ キューのさらに下のメソッドとイベント ハンドラーが、異なるキーの値を受け取るようにキーの値を変更することを表します。 このトピックでは、これらのタスクを実行する方法について説明します。

キーを使用するには

  • KeyPress イベント ハンドラーで、KeyPressEventArgs クラスの Handled プロパティを true に設定します。

    または

    KeyDown イベント ハンドラーで、KeyEventArgs クラスの Handled プロパティを true に設定します。

    注意

    KeyDown イベント ハンドラーで Handled プロパティを設定すると、KeyPress イベントと KeyUp イベントが現在のキー入力から発生しないようにすることができます。 この目的には、SuppressKeyPress プロパティを使用します。

    次の例は、KeyPress イベント ハンドラーによって受信された KeyPressEventArgsKeyChar プロパティを検査する switch ステートメントの抜粋です。 このコードは、'A' と 'a' 文字のキーを使用します。

    // Consume 'A' and 'a'.
    case (char)65:
    case (char)97:
        MessageBox.Show("Control.KeyPress: '" +
            e.KeyChar.ToString() + "' consumed.");
        e.Handled = true;
        break;
    
    ' Consume 'A' and 'a'.
    Case ChrW(65), ChrW(97)
        MessageBox.Show(("Control.KeyPress: '" + _
            e.KeyChar.ToString() + "' consumed."))
        e.Handled = True
    

標準の文字のキーを変更するには

  • KeyPress イベント ハンドラーで、KeyPressEventArgs クラスの KeyChar プロパティを新しい文字のキーの値に設定します。

    次の例は、'B' を 'A' に変更して、'b' を 'a' に変更する switch ステートメントの抜粋です。 KeyPressEventArgs パラメーターの Handled のプロパティが false に設定され、新しいキーの値が、メッセージ キューの他のメソッドとイベントに反映されることに注意してください。

    // Detect 'B', modify it to 'A', and forward the key.
    case (char)66:
        MessageBox.Show("Control.KeyPress: '" +
            e.KeyChar.ToString() + "' replaced by 'A'.");
        e.KeyChar = (char)65;
        e.Handled = false;
        break;
    
    // Detect 'b', modify it to 'a', and forward the key.
    case (char)98:
        MessageBox.Show("Control.KeyPress: '" +
            e.KeyChar.ToString() + "' replaced by 'a'.");
        e.KeyChar = (char)97;
        e.Handled = false;
        break;
    
        ' Modify 'B' to 'A' and forward the key.
    Case ChrW(66)
        MessageBox.Show(("Control.KeyPress: '" + _
            e.KeyChar.ToString() + "' replaced by 'A'."))
        e.KeyChar = ChrW(65)
        e.Handled = False
    
        ' Modify 'b' to 'a' and forward the key.
    Case ChrW(98)
        MessageBox.Show(("Control.KeyPress: '" + _
            e.KeyChar.ToString() + "' replaced by 'a'."))
        e.KeyChar = ChrW(97)
        e.Handled = False
    

非文字キーを変更するには

  • Windows メッセージを処理する Control メソッドをオーバーライドして、WM_KEYDOWN または WM_SYSKEYDOWN のメッセージを検出し、Message パラメーターの WParam プロパティを、新しい非文字キーを表す Keys 値に設定します。

    次のコード例は、F1 から F9 のキーを検出して、F3 キーを押したときに F1 に変更するよう、コントロールの PreProcessMessage メソッドをオーバーライドする方法を示しています、 キーボードのメッセージを代行受信するようにオーバーライドできる Control メソッドの詳細については、「Windows フォーム アプリケーションにおけるユーザー入力」と「キーボード入力のしくみ」を参照してください。

    // Detect F1 through F9 during preprocessing and modify F3.
    public override bool PreProcessMessage(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            Keys keyCode = (Keys)m.WParam & Keys.KeyCode;
    
            // Detect F1 through F9.
            switch (keyCode)
            {
                case Keys.F1:
                case Keys.F2:
                case Keys.F3:
                case Keys.F4:
                case Keys.F5:
                case Keys.F6:
                case Keys.F7:
                case Keys.F8:
                case Keys.F9:
    
                    MessageBox.Show("Control.PreProcessMessage: '" +
                      keyCode.ToString() + "' pressed.");
    
                    // Replace F3 with F1, so that ProcessKeyMessage will
                    // receive F1 instead of F3.
                    if (keyCode == Keys.F3)
                    {
                        m.WParam = (IntPtr)Keys.F1;
                        MessageBox.Show("Control.PreProcessMessage: '" +
                            keyCode.ToString() + "' replaced by F1.");
                    }
                    break;
            }
        }
    
        // Send all other messages to the base method.
        return base.PreProcessMessage(ref m);
    }
    
    ' Detect F1 through F9 during preprocessing and modify F3.
    Public Overrides Function PreProcessMessage(ByRef m As Message) _
        As Boolean
    
        If m.Msg = WM_KEYDOWN Then
            Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode
    
            ' Detect F1 through F9.
            Select Case keyCode
                Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _
                     Keys.F6, Keys.F7, Keys.F8, Keys.F9
    
                    MessageBox.Show(("Control.PreProcessMessage: '" + _
                        keyCode.ToString() + "' pressed."))
    
                    ' Replace F3 with F1, so that ProcessKeyMessage will  
                    ' receive F1 instead of F3.
                    If keyCode = Keys.F3 Then
                        m.WParam = CType(Keys.F1, IntPtr)
                        MessageBox.Show(("Control.PreProcessMessage: '" + _
                            keyCode.ToString() + "' replaced by F1."))
                    End If
            End Select
        End If
    
        ' Send all other messages to the base method.
        Return MyBase.PreProcessMessage(m)
    End Function
    

次のコード例は、前のセクションのコード例の完全なアプリケーションです。 アプリケーションは、TextBox クラスから派生したカスタム コントロールを使用して、キーボードの入力を使用して変更します。

using System;
using System.Drawing;
using System.Windows.Forms;

namespace KeyboardInput
{
    class Form1 : Form
    {
        // The following Windows message value is defined in Winuser.h.
        private int WM_KEYDOWN = 0x100;
        CustomTextBox CustomTextBox1 = new CustomTextBox();

        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        public Form1()
        {
            this.AutoSize = true;
            this.Controls.Add(CustomTextBox1);
            CustomTextBox1.KeyPress +=
                new KeyPressEventHandler(CustomTextBox1_KeyPress);
        }

        // Consume and modify several character keys.
        void CustomTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (e.KeyChar)
            {
                // Consume 'A' and 'a'.
                case (char)65:
                case (char)97:
                    MessageBox.Show("Control.KeyPress: '" +
                        e.KeyChar.ToString() + "' consumed.");
                    e.Handled = true;
                    break;

                // Detect 'B', modify it to 'A', and forward the key.
                case (char)66:
                    MessageBox.Show("Control.KeyPress: '" +
                        e.KeyChar.ToString() + "' replaced by 'A'.");
                    e.KeyChar = (char)65;
                    e.Handled = false;
                    break;

                // Detect 'b', modify it to 'a', and forward the key.
                case (char)98:
                    MessageBox.Show("Control.KeyPress: '" +
                        e.KeyChar.ToString() + "' replaced by 'a'.");
                    e.KeyChar = (char)97;
                    e.Handled = false;
                    break;
            }
        }
    }
    
    public class CustomTextBox : TextBox
    {
        // The following Windows message value is defined in Winuser.h.
        private int WM_KEYDOWN = 0x100;

        public CustomTextBox()
        {
            this.Size = new Size(100, 100);
            this.AutoSize = false;
        }

        // Detect F1 through F9 during preprocessing and modify F3.
        public override bool PreProcessMessage(ref Message m)
        {
            if (m.Msg == WM_KEYDOWN)
            {
                Keys keyCode = (Keys)m.WParam & Keys.KeyCode;

                // Detect F1 through F9.
                switch (keyCode)
                {
                    case Keys.F1:
                    case Keys.F2:
                    case Keys.F3:
                    case Keys.F4:
                    case Keys.F5:
                    case Keys.F6:
                    case Keys.F7:
                    case Keys.F8:
                    case Keys.F9:

                        MessageBox.Show("Control.PreProcessMessage: '" +
                          keyCode.ToString() + "' pressed.");

                        // Replace F3 with F1, so that ProcessKeyMessage will
                        // receive F1 instead of F3.
                        if (keyCode == Keys.F3)
                        {
                            m.WParam = (IntPtr)Keys.F1;
                            MessageBox.Show("Control.PreProcessMessage: '" +
                                keyCode.ToString() + "' replaced by F1.");
                        }
                        break;
                }
            }

            // Send all other messages to the base method.
            return base.PreProcessMessage(ref m);
        }

        // Detect F1 through F9 during processing.
        protected override bool ProcessKeyMessage(ref Message m)
        {
            if (m.Msg == WM_KEYDOWN)
            {
                Keys keyCode = (Keys)m.WParam & Keys.KeyCode;

                // Detect F1 through F9.
                switch (keyCode)
                {
                    case Keys.F1:
                    case Keys.F2:
                    case Keys.F3:
                    case Keys.F4:
                    case Keys.F5:
                    case Keys.F6:
                    case Keys.F7:
                    case Keys.F8:
                    case Keys.F9:

                        MessageBox.Show("Control.ProcessKeyMessage: '" +
                          keyCode.ToString() + "' pressed.");
                        break;
                }
            }

            // Send all messages to the base method.
            return base.ProcessKeyMessage(ref m);
        }
    }
}
Imports System.Drawing
Imports System.Security
Imports System.Security.Permissions
Imports System.Windows.Forms

Namespace KeyboardInput
    Class Form1
        Inherits Form

        ' The following Windows message value is defined in Winuser.h.
        Private WM_KEYDOWN As Integer = &H100
        Private WithEvents CustomTextBox1 As New CustomTextBox()

        <STAThread()> _
        Public Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub

        Public Sub New()
            Me.AutoSize = True
            Me.Controls.Add(CustomTextBox1)
        End Sub

        ' Consume and modify several character keys.
        Sub CustomTextBox1_KeyPress(ByVal sender As Object, _
            ByVal e As KeyPressEventArgs) Handles CustomTextBox1.KeyPress

            Select Case e.KeyChar

                ' Consume 'A' and 'a'.
                Case ChrW(65), ChrW(97)
                    MessageBox.Show(("Control.KeyPress: '" + _
                        e.KeyChar.ToString() + "' consumed."))
                    e.Handled = True

                    ' Modify 'B' to 'A' and forward the key.
                Case ChrW(66)
                    MessageBox.Show(("Control.KeyPress: '" + _
                        e.KeyChar.ToString() + "' replaced by 'A'."))
                    e.KeyChar = ChrW(65)
                    e.Handled = False

                    ' Modify 'b' to 'a' and forward the key.
                Case ChrW(98)
                    MessageBox.Show(("Control.KeyPress: '" + _
                        e.KeyChar.ToString() + "' replaced by 'a'."))
                    e.KeyChar = ChrW(97)
                    e.Handled = False
            End Select
        End Sub
    End Class

    Public Class CustomTextBox
        Inherits TextBox

        ' The following Windows message value is defined in Winuser.h.
        Private WM_KEYDOWN As Integer = &H100

        Public Sub New()
            Me.Size = New Size(100, 100)
            Me.AutoSize = False
        End Sub

        ' Detect F1 through F9 during preprocessing and modify F3.
        Public Overrides Function PreProcessMessage(ByRef m As Message) _
            As Boolean

            If m.Msg = WM_KEYDOWN Then
                Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode

                ' Detect F1 through F9.
                Select Case keyCode
                    Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _
                         Keys.F6, Keys.F7, Keys.F8, Keys.F9

                        MessageBox.Show(("Control.PreProcessMessage: '" + _
                            keyCode.ToString() + "' pressed."))

                        ' Replace F3 with F1, so that ProcessKeyMessage will  
                        ' receive F1 instead of F3.
                        If keyCode = Keys.F3 Then
                            m.WParam = CType(Keys.F1, IntPtr)
                            MessageBox.Show(("Control.PreProcessMessage: '" + _
                                keyCode.ToString() + "' replaced by F1."))
                        End If
                End Select
            End If

            ' Send all other messages to the base method.
            Return MyBase.PreProcessMessage(m)
        End Function

        ' Detect F1 through F9 during processing.
        Protected Overrides Function ProcessKeyMessage(ByRef m As Message) _
            As Boolean

            If m.Msg = WM_KEYDOWN Then
                Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode

                ' Detect F1 through F9.
                Select Case keyCode
                    Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _
                         Keys.F6, Keys.F7, Keys.F8, Keys.F9

                        MessageBox.Show(("Control.ProcessKeyMessage: '" + _
                            keyCode.ToString() + "' pressed."))
                End Select
            End If

            ' Send all messages to the base method.
            Return MyBase.ProcessKeyMessage(m)
        End Function

    End Class
End Namespace

コードのコンパイル

この例で必要な要素は次のとおりです。

  • System、System.Drawing、および System.Windows.Forms の各アセンブリへの参照。

関連項目