如何按住某个键?

时间:2016-12-14 15:49:23

标签: vb.net input keyboard wait

我正在创建一个程序,使用我的鼠标和键盘自动与另一个应用程序连接。我发现代码会点击一次键并立即释放(据我所知);这是SendKeys.Send(“{up}”)。如果可以的话,请不要过于复杂化,我在这里学习。

我的问题是如何发送按键并按住变量确定的一段时间。我大概想:

Press and hold arrow key "up"
wait(Random.next(1,10))
Release arrow key "up"

我在Visual Studio 17社区的Visual Basic中编写它。

谢谢!

在查看Valyrean Groups代码后,我将其编辑为:

Private Declare Sub keybd_event Lib "user32.dll" (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 Sub HoldKeyDown(ByVal key As Byte, ByVal durationInSeconds As Integer)

    keybd_event(key, MapVirtualKey(key, 0), 0, 0) ' Down
    Threading.Thread.Sleep((RandNum.Next(1000, 5000)))
    keybd_event(key, MapVirtualKey(key, 0), 2, 0) ' Up

End Sub

我现在的问题是如何更改按住的箭头键?

1 个答案:

答案 0 :(得分:-2)

您希望使用System32中的keybd事件库。将以下代码添加到表单中。

Private Declare Sub keybd_event Lib "user32.dll" (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 Sub HoldKeyDown(ByVal key As Byte, ByVal durationInSeconds As Integer)
    Dim targetTime As DateTime = DateTime.Now().AddSeconds(durationInSeconds)
    keybd_event(key, MapVirtualKey(key, 0), 0, 0) ' Down
    While targetTime.Subtract(DateTime.Now()).TotalSeconds > 0
        Application.DoEvents()
    End While
    keybd_event(key, MapVirtualKey(key, 0), 2, 0) ' Up
End Sub

然后使用它......

HoldKeyDown(Keys.Up,3)