How to: Modify Keyboard Input to a Standard Control

 

Windows Forms provides the ability to consume and modify keyboard input. Consuming a key refers to handling a key within a method or event handler so that other methods and events further down the message queue do not receive the key value. Modifying a key refers to modifying the value of a key so that methods and event handlers further down the message queue receive a different key value. This topic shows how to accomplish these tasks.

To consume a key

  • In a KeyPress event handler, set the Handled property of the KeyPressEventArgs class to true.

    -or-

    In a KeyDown event handler, set the Handled property of the KeyEventArgs class to true.

    System_CAPS_ICON_note.jpg Note

    Setting the Handled property in the KeyDown event handler does not prevent the KeyPress and KeyUp events from being raised for the current keystroke. Use the SuppressKeyPress property for this purpose.

    The following example is an excerpt from a switch statement that examines the KeyChar property of the KeyPressEventArgs received by a KeyPress event handler. This code consumes the 'A' and 'a' character keys.

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

To modify a standard character key

  • In a KeyPress event handler, set the KeyChar property of the KeyPressEventArgs class to the value of the new character key.

    The following example is an excerpt from a switch statement that modifies 'B' to 'A' and 'b' to 'a'. Note that the Handled property of the KeyPressEventArgs parameter is set to false, so that the new key value is propagated to other methods and events in the message queue.

                        ' 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
    

To modify a noncharacter key

  • Override a Control method that processes Windows messages, detect the WM_KEYDOWN or WM_SYSKEYDOWN message, and set the WParam property of the Message parameter to the Keys value that represents the new noncharacter key.

    The following code example demonstrates how to override the PreProcessMessage method of a control to detect keys F1 through F9 and modify any F3 key press to F1. For more information on Control methods that you can override to intercept keyboard messages, see User Input in a Windows Forms Application and How Keyboard Input Works.

            ' 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
    

The following code example is the complete application for the code examples in the previous sections. The application uses a custom control derived from the TextBox class to consume and modify keyboard input.

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

This example requires:

  • References to the System, System.Drawing and System.Windows.Forms assemblies.

For information about building this example from the command line for Visual Basic or Visual C#, see Building from the Command Line or Command-line Building With csc.exe. You can also build this example in Visual Studio by pasting the code into a new project. Also see How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio.

Keyboard Input in a Windows Forms Application
User Input in a Windows Forms Application
How Keyboard Input Works

Show: