这有点棘手,但如何记录按键的时间?我的目标是记录我按下的键和按下这些键的时间,然后能够以编程方式使用该记录。
答案 0 :(得分:0)
你的问题不是太具体,因此有许多替代方案适合那里。如果你想要的是对这个问题的处理方式的粗略介绍,你可以在这里得到一些帮助:
Public Class Form1
Dim allStartTimes(50) As Date
Dim allElapsedTimes(50) As TimeSpan
Dim allKeys(50) As Keys
Dim curIndex As Integer = 0
Dim totKeys As Integer = 50
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
Dim count As Integer = 0
Do
count = count + 1
If (e.KeyCode = allKeys(count)) Then
If (curIndex <> count) Then
If (curIndex > 0) Then
allElapsedTimes(curIndex) = Now.Subtract(allStartTimes(curIndex))
End If
allStartTimes(count) = Now
curIndex = count
Exit Do
End If
End If
Loop While (count < totKeys)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
allKeys(1) = Windows.Forms.Keys.A
allKeys(2) = Windows.Forms.Keys.B
'.....
End Sub
End Class
此代码显示了基本算法和获取密钥的一种替代方法:给定对象的KeyDown / KeyUp事件(在这种情况下,它是主要形式;请记住,仅在选择主窗体时才有效)。我没有包含KeyUp部分,因为需要一些工作来同步两个事件并使其正常工作(你应该做什么)。此代码不会存储给定键停止按下的时间,而是按下不同的键时。
事件的一个替代方案是钩子。它们在任何地方工作(不需要选择特定的对象),但也有它们的缺点。这里有一个有效的代码:
Public Class Form1
Private Const WM_HOTKEY As Integer = &H312
Private Declare Function RegisterHotKey Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal id As Integer, ByVal fsModifier As Integer, ByVal vk As Integer) As Integer
Private Declare Function UnregisterHotKey Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal id As Integer) As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RegisterHotKey(Me.Handle, 0, Nothing, Keys.A)
RegisterHotKey(Me.Handle, 0, Nothing, Keys.B)
'.....
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If (m.Msg = WM_HOTKEY AndAlso m.WParam = CType(0, IntPtr)) Then
If (m.LParam = CType(4259840, IntPtr)) Then
'A
ElseIf (m.LParam = CType(4325376, IntPtr)) Then
'B
End If
'.....
End If
MyBase.WndProc(m)
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
UnregisterHotKey(Me.Handle, 0)
End Sub
End Class
List of parameters for all the keys to run the hook above。显示的A&amp; B整数值仅仅是用于说明目的的快速解决方案。
即使还有其他选择,例如依赖WPF:an example of a C# implementation。
这些是基本的想法。如果你想要一个合适可靠的代码,你必须做一些研究和测试,以解决所有可能的可能性。