这有点棘手,但我如何记录按键的按下时间?我的目标是记录我按下的键和按下这些键的时间,然后能够在需要时以编程方式使用该记录。
问问题
1250 次
1 回答
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
运行上述钩子的所有键的参数列表。所示的 A 和 B 整数值仅代表用于说明目的的快速解决方案。
甚至还有其他选择,例如依赖 WPF:C# implementation 的示例。
这些是基本的想法。如果您想要一个适当且可靠的代码,则必须进行一些研究和测试以考虑所有可能的可能性。
于 2013-06-17T10:38:45.897 回答