[VB.NET]调用API获取/设置键盘按键状态

1.调用GetAsyncKeyState()获取指定按键的状态,GetActiveKey()检索指定范围内的按键状态

2.调用keybd_event()可合成一次击键事件,通常两次击键事件间需要设定时间间隔

3.调用MapVirtualKey()获取指定按键的硬件扫描码,传入keybd_event()第二个参数就可以对DirectInput有效。

Public Class ImitateKeyClass
    Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)
    Private Declare Function MapVirtualKey Lib "user32" Alias "MapVirtualKeyA" (ByVal wCode As Integer, ByVal wMapType As Integer) As Integer
    Private Declare Function GetAsyncKeyState Lib "user32 " (ByVal vKey As Integer) As Integer
    ''' <summary>
    ''' 发送按键
    ''' </summary>
    ''' <param name="CharArray"></param>
    Public Sub SendString(CharArray As String)
        For Each SubChar As Char In CharArray
            keybd_event(Asc(SubChar), MapVirtualKey(Asc(SubChar), 0), &H1 Or 0, 0) '按下
            System.Threading.Thread.Sleep(10) '延时
            keybd_event(Asc(SubChar), MapVirtualKey(Asc(SubChar), 0), &H1 Or &H2, 0) '弹起
            System.Threading.Thread.Sleep(10)
        Next
    End Sub
    ''' <summary>
    '''  获取A~Z的按键状态
    ''' </summary>
    ''' <returns></returns>
    Public Function GetActiveKey() As Byte
        For i = 65 To 90 'A~Z的ASICC码
            If CurrentKeyState(i) = True Then Return i
        Next
        Return 0
    End Function
    ''' <summary>
    ''' 获取键盘按键状态
    ''' </summary>
    ''' <param name="KeyCode"></param>
    ''' <returns></returns>
    Private Function CurrentKeyState(ByVal KeyCode As Byte) As Boolean
        Dim temp As Integer = GetAsyncKeyState(KeyCode)
        Return (IIf(temp = -32767, True, False))
    End Function
End Class

 

你可能感兴趣的:([VB.NET]调用API获取/设置键盘按键状态)