HOW TO:將鍵盤輸入修改為標準控制項

Windows Form 提供使用和修改鍵盤輸入的能力。 使用按鍵表示在方法或事件處理常式中處理按鍵,因此訊息佇列中後面的其他方法和事件並不會收到按鍵值。 修改按鍵表示修改按鍵的值,因此訊息佇列中後面的方法和事件處理常式會收到不同的按鍵值。 本主題將示範如何完成這些工作。

若要使用按鍵

  • KeyPress 事件處理常式中,將 KeyPressEventArgs 類別的 Handled 屬性設定為 true。

    -或-

    KeyDown 事件處理常式中,將 KeyEventArgs 類別的 Handled 屬性設定為 true。

    注意事項注意事項

    KeyDown 事件處理常式中設定 Handled 屬性,並不會防止引發目前按鍵的 KeyPressKeyUp 事件。 為了這個目的,請使用 SuppressKeyPress 屬性。

    下列範例摘錄自 switch 陳述式,它會檢查 KeyPress 事件處理常式所收到的 KeyPressEventArgsKeyChar 屬性。 此程式碼會使用 'A' 和 'a' 字元按鍵。

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

若要修改標準的字元按鍵

  • KeyPress 事件處理常式中,將 KeyPressEventArgs 類別的 KeyChar 屬性設定為新字元按鍵的值。

    下列範例摘錄自 switch 陳述式,它會將 'B' 修改為 'A' 及將 'b' 修改為 'a'。 請注意,KeyPressEventArgs 參數的 Handled 屬性會設定為 false,因此新按鍵值會傳送至訊息佇列中的其他方法和事件。

        ' 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
    
    // 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;
    

若要修改非字元按鍵

  • 覆寫處理 Windows 訊息的 Control 方法、偵測 WM_KEYDOWN 或 WM_SYSKEYDOWN 訊息,並將 Message 參數的 WParam 屬性設定為表示新非字元按鍵的 Keys 值。

    下列程式碼範例示範如何覆寫控制項的 PreProcessMessage 方法,以偵測按鍵 F1 至 F9,並將任何按下的 F3 按鍵修改為 F1。 如需您可以覆寫以攔截鍵盤訊息的 Control 方法的詳細資訊,請參閱Windows Form 應用程式中的使用者輸入鍵盤輸入的運作方式

    ' 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 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);
    }
    

範例

下列程式碼範例是前面幾節中程式碼範例的完整應用程式。 此應用程式使用衍生自 TextBox 類別的自訂控制項來使用和修改鍵盤輸入。

Imports System
Imports System.Drawing
Imports System.Security
Imports System.Security.Permissions
Imports System.Windows.Forms


Namespace KeyboardInput
<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _ 
    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

<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _ 
    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
using System;
using System.Drawing;
using System.Windows.Forms;

namespace KeyboardInput
{
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
    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;
            }
        }
    }
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
    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);
        }
    }
}

編譯程式碼

這個範例需要:

  • System、System.Drawing 和 System.Windows.Forms 組件的參考。

如需從 Visual Basic 或 Visual C# 的命令列建置這個範例的詳細資訊,請參閱從命令列建置 (Visual Basic)使用 csc.exe 建置命令列。 您也可以透過將程式碼貼入新的專案,在 Visual Studio 中建置此範例。 如需詳細資訊,請參閱HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例如何:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例.

請參閱

概念

Windows Form 應用程式中的使用者輸入

鍵盤輸入的運作方式

其他資源

Windows Form 應用程式中的鍵盤輸入