2016-12-14 188 views
-2

我正在創建一個程序,使用我的鼠標和鍵盤自動與另一個應用程序進行交互。我發現代碼會立即點擊該鍵並立即釋放它(據我所知);這是SendKeys.Send(「{up}」)。請不要過於複雜的事情,如果你可以,即時在這裏學習。如何按住按鍵?

我的問題是如何發送按鍵,並保持一段時間由變量決定。我大致想要:

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

我在Visual Studio 17社區中使用Visual Basic編寫它。

謝謝!

看着Valyrean組代碼後,我已經編輯它歸結爲這樣:

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 

我的問題是現在我該怎樣改變箭頭鍵被按下並保持?

+0

忽略此編輯 – Norman

+0

FYI'keybd_event()'已過時,被替換爲[**'SendInput()'**](HTTPS ://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v = vs.85).aspx) –

回答

-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) 
+0

感謝您的迴應,雖然這可能會工作我尋找的東西儘可能簡單。我使用定時器來幫助保持長度;這可以讓它更容易嗎?我想重複這個箭頭的所有方向(上,下,左,右),以便它可能成爲一個相當大的工作 – Norman

+0

代碼不會變得更大。這很簡單...要「保留」另一個鍵,只需使用另一個鍵和時間再次調用該功能即可。 – TheValyreanGroup

+0

謝謝請參閱我的編輯:) – Norman