检测某些按键何时按下并释放

时间:2013-10-14 20:03:48

标签: vb.net

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

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

无法找到检测用户何时释放密钥的方法

如何根据按键自动检测按键和发送键?

感谢anyhelp

2 个答案:

答案 0 :(得分:1)

首先,为了获得类似的工作,您需要为表单设置KeyPreview = True。接下来,您可能希望使用KeyDown事件。捕获任何密钥(Keys.F1),只要密钥关闭,您就会收到针对垃圾邮件F1的keydown事件。

我们今天在键盘陷阱上有一个特别的。 See this也是如此。除此之外,你必须自己尝试一些。这就是你学习的方式。遇到困难时,请发布您的代码。

您还可以搜索标记为VB NET / 6的60,059个问题来查找样本。

答案 1 :(得分:0)

我找到了做到这一点的方法

这里我将发布代码,如果有人在寻找它,这就是答案

Imports System.Windows.Forms
Imports MouseKeyboardActivityMonitor
Imports MouseKeyboardActivityMonitor.WinApi
Imports System.Runtime.InteropServices.DllImportAttribute
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System

Public Class Form1
Private Declare Function GetAsyncKeyState Lib "User32" (ByVal vKey As Keys) As Integer

<DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function SendInput(ByVal nInputs As Integer, ByRef pInputs As NativeMethods.INPUT, ByVal cbSize As Integer) As Integer
End Function
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 Sub DoKeyBoard(ByVal flags As NativeMethods.KEYEVENTF, ByVal key As Keys)
    Dim input As NativeMethods.INPUT
    Dim ki As NativeMethods.KEYBDINPUT
    input.type = NativeMethods.InputType.Keyboard
    input.u.ki = ki
    input.u.ki.wVk = Convert.ToInt16(key)
    input.u.ki.wScan = 0
    input.u.ki.time = 0
    input.u.ki.dwFlags = flags
    input.u.ki.dwExtraInfo = IntPtr.Zero
    Dim cbSize As Integer = Marshal.SizeOf(GetType(NativeMethods.INPUT))
    Dim result As Integer = NativeMethods.SendInput(1, input, cbSize)
    If result = 0 Then Debug.WriteLine(Marshal.GetLastWin32Error)
End Sub

Private WithEvents myKeyboardHookManager As KeyboardHookListener
Dim hookEnabled As Boolean
Public Sub New()
    InitializeComponent()
    myKeyboardHookManager = New KeyboardHookListener(New GlobalHooker())
    myKeyboardHookManager.
相关问题