按键和释放时执行某些操作

时间:2013-10-14 22:08:11

标签: vb.net

看起来我的旧问题已经遗留下来了

我很难找到一种方法来做到这一点

我希望我的应用程序在按键时执行某些操作。例如,当用户按F1时,只要F1仍然按下,它就会发送键F1,当用户释放F1时,它不会发送键F1。

我无法找到让我的应用程序在F1发布前按F1的方法

这是代码

Imports System.Windows.Forms
Imports MouseKeyboardActivityMonitor
Imports MouseKeyboardActivityMonitor.WinApi

Public Class Form1

Private Declare Function GetAsyncKeyState Lib "User32" (ByVal vKey As Keys) As Integer
Public Declare Sub mouse_event Lib "User32" Alias "mouse_event" (ByVal dwFlags As Integer, ByVal dx As Integer, ByVal dy As Integer, ByVal cButtons As Integer, ByVal dwExtraInfo As Integer)
Public Const MOUSEEVENTF_LEFTDOWN = &H2 ' left button down
Public Const MOUSEEVENTF_LEFTUP = &H4 ' left button up

Private WithEvents myKeyboardHookManager As KeyboardHookListener
Dim hookEnabled As Boolean
Public Sub New()
    InitializeComponent()
    myKeyboardHookManager = New KeyboardHookListener(New GlobalHooker())
    myKeyboardHookManager.Enabled = True
End Sub

Private Sub HookManager_KeyDown(sender As Object, e As KeyEventArgs)
    Select Case e.KeyCode
        Case Keys.F1 To Keys.F9
            SendKeys.Send("{F" + Convert.ToChar(e.KeyValue - 63) + "}")
    End Select
    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If hookEnabled Then
        hookEnabled = False
        RemoveHandler myKeyboardHookManager.KeyDown, AddressOf HookManager_KeyDown
    Else
        hookEnabled = True
        AddHandler myKeyboardHookManager.KeyDown, AddressOf HookManager_KeyDown
    End If
End Sub
End Class

此代码工作正常,但只按一次。我想要的是它在我发布之前继续按下

感谢anyhelp

0 个答案:

没有答案