在nuget中安装sharpdx插件
使用:
directInput = New DirectInput()
Dim Devices = directInput.GetDevices(DeviceType.Keyboard, DeviceEnumerationFlags.AllDevices)
For Each device In Devices
If (device.Type = SharpDX.DirectInput.DeviceType.Keyboard) Then
MyKeyboard = New SharpDX.DirectInput.Keyboard(directInput)
MyKeyboard.Acquire()
End If
Next
'启动timer
Mytimer.Interval = New TimeSpan(0, 0, 0, 0, 12)
AddHandler Mytimer.Tick, AddressOf CheckKeyboard
Mytimer.Start()
然后在timer中检测按键如下:
Private Sub CheckKeyboard(sender As Object, e As EventArgs)
Dim curKeyboardState = MyKeyboard.GetCurrentState()
'上方向键
If curKeyboardState.IsPressed(Key.Up) Then
Border_up.Background = key_pressd_color
tup.Foreground = text_pressed_color
Else
Border_up.Background = key_released_color
tup.Foreground = text_released_color
End If
'左方向键
If curKeyboardState.IsPressed(Key.Left) Then
Border_left.Background = key_pressd_color
tleft.Foreground = text_pressed_color
Else
Border_left.Background = key_released_color
tleft.Foreground = text_released_color
End If
'下方向键
If curKeyboardState.IsPressed(Key.Down) Then
Border_down.Background = key_pressd_color
tdown.Foreground = text_pressed_color
Else
Border_down.Background = key_released_color
tdown.Foreground = text_released_color
End If
'右方向键
If curKeyboardState.IsPressed(Key.Right) Then
Border_right.Background = key_pressd_color
tright.Foreground = text_pressed_color
Else
Border_right.Background = key_released_color
tright.Foreground = text_released_color
End If
'shieft键
If curKeyboardState.IsPressed(Key.LeftShift) Or curKeyboardState.IsPressed(Key.RightShift) Then
Border_shift.Background = key_pressd_color
tshift.Foreground = text_pressed_color
Else
Border_shift.Background = key_released_color
tshift.Foreground = text_released_color
End If
'ctrl键
If curKeyboardState.IsPressed(Key.RightControl) Or curKeyboardState.IsPressed(Key.LeftControl) Then
Border_ctrl.Background = key_pressd_color
tctrl.Foreground = text_pressed_color
Else
Border_ctrl.Background = key_released_color
tctrl.Foreground = text_released_color
End If
End Sub
详情参考:
https://github.com/songshizhao/DxKeyboard