最小化界面时,热键不起作用

问题描述

我使用计时器和几个按钮在Visual Basic中创建了一个简单的自动答题器。

我为我的开始和停止按钮分配了键绑定,但是它们仅在打开接口时才起作用,并且我想在程序最小化时使用它们。

我该怎么做呢?以下是一些更重要的上下文代码。如果您需要更多信息,请告诉我。

Declare Sub mouse_event Lib "user32.dll" Alias "mouse_event" (ByVal dwFlags As Int32,ByVal dx As Int32,ByVal cButtons As Int32,ByVal dwExtraInfo As Int32,v As Integer)

Private Sub frmAutoClicker_KeyPress(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Z) Then
            btnStart.PerformClick()
        End If
  End Sub
 Private Sub btnStart_Click(sender As Object,e As EventArgs) Handles btnStart.Click

        Timer1.Start()

    End Sub
Private Sub Timer1_Tick(sender As Object,e As EventArgs) Handles Timer1.Tick
        mouse_event(&H2,1)
        mouse_event(&H4,1)
End Sub

解决方法

您可以尝试从user32.dll中尝试SetWindowsHookEx,这是一种激进的方法...但是它可以工作。(在此论坛中搜索SetWindowsHookEx ...)

或者您可以尝试向应用程序添加消息过滤器:

Application.AddMessageFilter
,

您可以使用RegisterHotkey来实现VB.NET在最小化的情况下检测按键。
这是了解Virtual-Key Codes的第一步。

为了便于测试,我设置了Timer1_Tick的自动点击限制,该限制被限制为50次。

示例代码:

Imports System.Runtime.InteropServices

Public Class frmAutoClicker
Public Const WM_HOTKEY As Integer = &H312

Public Const VK_1 As Integer = &H5A   '0x5A  Z key
Dim i As Integer = 0

<DllImport("User32.dll")>
Public Shared Function RegisterHotKey(ByVal hwnd As IntPtr,ByVal id As Integer,ByVal fsModifiers As Integer,ByVal vk As Integer) As Integer
End Function

<DllImport("User32.dll")>
Public Shared Function UnregisterHotKey(ByVal hwnd As IntPtr,ByVal id As Integer) As Integer
End Function

Declare Sub mouse_event Lib "user32.dll" Alias "mouse_event" (ByVal dwFlags As Int32,ByVal dx As Int32,ByVal cButtons As Int32,ByVal dwExtraInfo As Int32,v As Integer)

Private Sub frmAutoClicker_Load(sender As Object,e As EventArgs) Handles MyBase.Load
    Dim retVal1 As Boolean = RegisterHotKey(Me.Handle,10,VK_1)
    If retVal1 = False Then
        MsgBox("The hotkeys could not be registered!",MsgBoxStyle.Critical)
        Application.Exit()
    End If
End Sub

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_HOTKEY Then
        Dim id As IntPtr = m.WParam
        Select Case (id.ToString)
            Case "10"
                btnStart.PerformClick()
       End Select
    End If
    MyBase.WndProc(m)
End Sub

Private Sub frmAutoClicker_FormClosing(sender As Object,e As FormClosingEventArgs) Handles MyBase.FormClosing
    UnregisterHotKey(Me.Handle,10)
End Sub
Private Sub btnStart_Click(sender As Object,e As EventArgs) Handles btnStart.Click
    Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object,e As EventArgs) Handles Timer1.Tick
    If i > 50 Then
        Timer1.Stop()
        i = 0
    Else
        mouse_event(&H2,1)
        mouse_event(&H4,1)
    End If
    i = i + 1
End Sub

End Class

结果:

enter image description here