Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

How to handle keyboard input messages in the form

Feedback

In this article

Windows Forms provides the ability to handle keyboard messages at the form level, before the messages reach a control. This article shows how to accomplish this task.

Handle a keyboard message

Handle theKeyPress orKeyDown event of the active form and set theKeyPreview property of the form totrue. This property causes the keyboard to be received by the form before they reach any controls on the form. The following code example handles theKeyPress event by detecting all of the number keys and consuming1,4, and7.

// 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;        }    }}
' 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.Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs)    If e.KeyChar >= Chr(48) And e.KeyChar <= Chr(57) Then        MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed.")        Select Case e.KeyChar            Case Chr(49), Chr(52), Chr(55)                MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed.")                e.Handled = True        End Select    End IfEnd Sub

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?