1

我很难找到一种方法来做到这一点。

我希望我的应用程序在用户按下数字键盘上的某个键时为用户显示一个消息框。主要问题是它必须在表格失焦的情况下完成。找不到使用 VB.NET 的任何方法

4

2 回答 2

2

宣布 :

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Integer) As Integer
Dim result As Integer

表单加载:

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 

:)

于 2012-11-02T01:25:26.117 回答
1

您实际上在谈论的是全局键盘钩子,因为您想收听不是针对您的程序的消息。CodePlex 上有一个很好的库(应用程序和全局鼠标和键盘挂钩库),它为.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
于 2012-11-02T06:00:32.793 回答