我在设法找到方法时遇到了麻烦。
我希望我的应用程序在按下小键盘上的某个键时为用户显示一个消息框。主要问题是它必须以焦点形式完成。使用VB.NET无法找到任何方法
答案 0 :(得分:2)
声明:
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Integer) As Integer
Dim result As Integer
formload:
Timer1.interval = 1
timer1.start()
Timer1.tick:
For i = 1 To 255
result = 0
result = GetAsyncKeyState (i)
If result = -32767 Then
If i = 103 Then
MsgBox("Num 7")
End If
End If
Next i
:)
答案 1 :(得分:1)
您实际谈论的内容称为Global KeyboardHook,因为您想要收听不是针对您的程序的消息。 CodePlex(Application and Global Mouse and Keyboard Hooks Library)上有一个很好的库,可以为.Net实现这个。
这是一个非常简单的示例,您需要下载上面的库并将MouseKeyboardActivityMonitor
添加到您的参考文献中。
Imports MouseKeyboardActivityMonitor
Imports MouseKeyboardActivityMonitor.WinApi
Public Class Form1
Private WithEvents myKeyboardHookManager As KeyboardHookListener
Dim hookEnabled As Boolean
Public Sub New()
InitializeComponent()
myKeyboardHookManager = New KeyboardHookListener(New GlobalHooker())
myKeyboardHookManager.Enabled = True
End Sub
Private Sub HookManager_KeyDown(sender As Object, e As KeyEventArgs)
Select Case e.KeyCode
Case Keys.NumPad0 To Keys.NumPad9
MessageBox.Show("KeyCode = " & e.KeyCode & vbCrLf & "Number = " & (e.KeyCode - 96))
End Select
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If hookEnabled Then
hookEnabled = False
RemoveHandler myKeyboardHookManager.KeyDown, AddressOf HookManager_KeyDown
Else
hookEnabled = True
AddHandler myKeyboardHookManager.KeyDown, AddressOf HookManager_KeyDown
End If
End Sub
End Class