界面最小化时热键不起作用
Posted
技术标签:
【中文标题】界面最小化时热键不起作用【英文标题】:Hotkey doesn't work while interface is minimized 【发布时间】:2021-01-30 17:59:25 【问题描述】:我使用计时器和几个按钮在 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, 0, 0, 0, 1)
mouse_event(&H4, 0, 0, 0, 1)
End Sub
【问题讨论】:
【参考方案1】:你可以从 user32.dll 中尝试 SetWindowsHookEx,这是一种激进的方法......但它会起作用......(在这个论坛中搜索 SetWindowsHookEx......)
或者您可以尝试向应用程序添加消息过滤器:
Application.AddMessageFilter
【讨论】:
谢谢。我会试试看它是否有效【参考方案2】:您可以使用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, 0, 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, 0, 0, 0, 1)
mouse_event(&H4, 0, 0, 0, 1)
End If
i = i + 1
End Sub
End Class
结果:
【讨论】:
以上是关于界面最小化时热键不起作用的主要内容,如果未能解决你的问题,请参考以下文章