我为全屏游戏制作了叠加扩展程序。我想在游戏中使用热键激活不同的命令。我曾经使用GetAsyncKeyState
,然后使用计时器不断检查KeyState
是否已更改。然后我切换到使用RegisterHotKey
函数,如下所示:
Imports System.Runtime.InteropServices
Public Class Form1
Public Const MOD_ALT As Integer = &H1 'Alt key
Public Const MOD_CONTROL As Integer = &H2 'CTRL key
Public Const MOD_SHIFT As Integer = &H4 'Shift key
Public Const MOD_NOREPEAT As Integer = &H4000 'NoRepeat
Public Const MOD_WIN As Integer = &H8 'Windows key
Public Const WM_HOTKEY As Integer = &H312
<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
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RegisterHotKey(Me.Handle, 1, MOD_CONTROL + MOD_ALT + MOD_NOREPEAT, Keys.D)
RegisterHotKey(Me.Handle, 2, MOD_ALT, Keys.C)
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 "1"
MessageBox.Show("You pressed CTRL+ALT+D key combination")
Case "2"
MessageBox.Show("You pressed ALT+C key combination")
End Select
End If
MyBase.WndProc(m)
End Sub
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
UnregisterHotKey(Me.Handle, 1)
UnregisterHotKey(Me.Handle, 2)
End Sub
End Class
这很完美,即使我按住热键,我也可以使用noRepeat只触发一次这个函数,这是我在使用GetAsyncKeyState
和计时器时遇到的问题。我的问题是,当我进入游戏时,表单不会注册按键。当我在任何其他没有全屏运行的程序时,它检测到热键就好了。我应该回到GetAsyncKeyState
还是有另一种检测热键的方法,即使在全屏游戏中也是如此?