我正在VB.NET中创建一个热键程序,它可以检测来自不同程序的组合键,并输入一个字符串。我正在使用全局热键来检测按键,但有些应用程序会拦截按键,并阻止它们到达我的程序。例如,在Chrome中,按CTRL + T将打开一个新标签。此外,这在Windows中发生,一些键组合(如CTRL + ALT + A)键入不同的键(在这种情况下为á)。
我需要阻止这一点。
我的代码目前看起来像这样:
Imports System.Runtime.InteropServices
Public Class Form1
Public Const alphabet = "abcdefghijklmnopqrstuvwxyz"
Dim currentNum As Integer = 0
#Region "Hotkey stuff"
Public Const MOD_NONE As Integer = &H0
Public Const MOD_ALT As Integer = &H1
Public Const MOD_CTRL As Integer = &H2
Public Const MOD_CTRL_ALT As Integer = &H3
Public Const MOD_SHIFT As Integer = &H4
Public Const MOD_CTRL_SHIFT As Integer = &H6
Public Const MOD_CTRL_ALT_SHIFT As Integer = &H7
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
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"
SendKeys.Send("Test")
End Select
End If
MyBase.WndProc(m)
End Sub
#End Region
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.SelectedItem = ComboBox1.Items.Item(0)
ComboBox2.SelectedItem = ComboBox2.Items.Item(0)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox2.SelectedIndex = 0 Then
MsgBox("Please select a key.")
Exit Sub
End If
currentNum += 1
RegisterHotKey(Me.Handle, currentNum, getModKeyCode(ComboBox1.SelectedItem.ToString), getKeyCode(ComboBox2.SelectedItem.ToString))
End Sub
Function getKeyCode(keyText As String)
If alphabet.Contains(keyText) Then
Return Asc(keyText) - 32
ElseIf IsNumeric(keyText) Then
Return CInt(keyText) + 48
ElseIf keyText.StartsWith("F") Then
Return CInt(keyText.Remove(0, 1)) + 111
ElseIf "[]#;',./\|*-+=".Contains(keyText) Then
If keyText = "[" Then
Return 219
ElseIf keyText = "\" Then
Return 220
ElseIf keyText = "]" Then
Return 221
End If
End If
Return Keys.A
End Function
Function getModKeyCode(modText As String)
If modText = "CTRL" Then
Return MOD_CTRL
ElseIf Text = "ALT" Then
Return MOD_ALT
ElseIf modText = "SHIFT" Then
Return MOD_SHIFT
ElseIf modText = "CTRL + ALT" Then
Return MOD_CTRL_ALT
ElseIf modText = "CTRL + SHIFT" Then
Return MOD_CTRL_SHIFT
ElseIf modText = "CTRL + ALT + SHIFT" Then
Return MOD_CTRL_ALT_SHIFT
Else
Return MOD_NONE
End If
End Function
End Class