在keydown事件中区分输入键

时间:2014-12-09 11:38:38

标签: vb.net keydown

如果在VB.net中使用Keydown处理程序按下回车键,则可以检测到回车键:

Private Sub kd(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
     IF e.key=key.Enter Then
       <do your code>
     Endif
End Sub

但是,是否有方法可以判断键盘中的两个输入键中的哪一个被按下?由于键盘中有两个输入键(一个在撇号(中间)旁边,另一个在数字键),我想让中间输入按钮有一个来自小键盘输入按钮的不同响应。

一个例子:在photoshop中,当使用文字工具时,你可以按中间输入添加另一行文字,或者按小键盘输入来确认你打字了。

1 个答案:

答案 0 :(得分:3)

取自http://support.microsoft.com/kb/188550/en-us

VB.net中的代码

Option Strict Off
Option Explicit On
Friend Class Form1
    Inherits System.Windows.Forms.Form
    Private Declare Function PeekMessage Lib "user32" Alias "PeekMessageA" (ByRef lpMsg As MSG, ByVal hwnd As Integer, ByVal wMsgFilterMin As Integer, ByVal wMsgFilterMax As Integer, ByVal wRemoveMsg As Integer) As Integer

    Private Structure POINTAPI
        Dim x As Integer
        Dim y As Integer
    End Structure

    Private Structure MSG
        Dim hwnd As Integer
        Dim message As Integer
        Dim wParam As Integer
        Dim lParam As Integer
        Dim time As Integer
        Dim pt As POINTAPI
    End Structure

    Const PM_NOREMOVE As Integer = &H0
    Const WM_KEYDOWN As Integer = &H100
    Const WM_KEYUP As Integer = &H101
    Const VK_RETURN As Integer = &HD

    Private Sub Form1_KeyDown(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        Dim KeyCode As Short = eventArgs.KeyCode
        Dim Shift As Short = eventArgs.KeyData \ &H10000
        Dim MyMsg As MSG
        Dim RetVal As Integer

        ' pass:
        '   MSG structure to receive message information
        '   my window handle
        '   low and high filter of 0, 0 to trap all messages
        '   PM_NOREMOVE to leave the keystroke in the message queue
        '   use PM_REMOVE (1) to remove it
        RetVal = PeekMessage(MyMsg, Me.Handle.ToInt32, 0, 0, PM_NOREMOVE)

        ' now, per Q77550, you should look for a MSG.wParam of VK_RETURN
        ' if this was the keystroke, then test bit 24 of the lparam - if ON,
        ' then keypad was used, otherwise, keyboard was used
        If RetVal <> 0 Then
            If MyMsg.wParam = VK_RETURN Then
                If MyMsg.lParam And &H1000000 Then
                    MsgBox("Enter from Keypad pressed")
                Else
                    MsgBox("Enter from Keyboard pressed")
                End If
            End If
        Else
            MsgBox("No message waiting, or possible problems calling PeekMessage")
        End If
    End Sub
End Class