我试图在用户输入时计算每毫秒字符的输入速度。我有两个控件,richtextbox和文本框作为输入区域,当用户在文本区域中键入时,字符之间的速度显示在richtextbox中。
Public Class Form1
Dim swatch As New Stopwatch
Dim finalSpeed As Double
Dim temp As Double
Private Sub typingArea_KeyPressed(sender As Object, e As KeyPressEventArgs) Handles typingArea.KeyPress
swatch.Start()
If swatch.IsRunning Then
temp += swatch.ElapsedMilliseconds
End If
If e.KeyChar = ChrW(Keys.Return) Then
e.KeyChar = Nothing
swatch.Reset()
MsgBox(finalSpeed / typingArea.Text.Length)
typingArea.Text = Nothing
logArea.Text = Nothing
End If
If typingArea.Text <> Nothing Then
swatch.Start()
End If
If swatch.IsRunning = False Then swatch.Start()
If typingArea.Text.Length > 0 Then
logArea.AppendText("time between two chars is " + temp.ToString() + Environment.NewLine)
finalSpeed += temp
temp = 0
swatch.Restart()
'End If
Else
swatch.Reset()
End If
End Sub
Public Function returnAverageSpeed(ByVal length As Integer, ByVal total As Double) As Double
Return total / length
End Function
End Class
如果文本框中只有一个字符,则无需计算速度,但如果用户键入第二个字符和后续字符,则我们开始计算速度。如果用户按下回车键,我们计算的平均速度将停止该过程,直到用户再次开始在文本框中键入。这里的问题是,程序无法记录第一个和第二个字符之间的速度,但其他人似乎现在正常工作。
答案 0 :(得分:1)
老实说,代码有点难读。而且我不确定为什么两个按键之间的第一个间隙不起作用。但重写了一下,它似乎工作。
Private Sub typingArea_KeyPressed(sender As Object, e As KeyPressEventArgs) Handles typingArea.KeyPress
'if the stopwatch is running add elapsed time. Otherwise start the stopwatch
If swatch.IsRunning Then
temp = swatch.ElapsedMilliseconds
finalSpeed += temp
Else
swatch.Start()
End If
'if user presses return, pop up the message box, reset the swatch, clear the boxes and exit the sub
If e.KeyChar = ChrW(Keys.Return) Then
e.KeyChar = Nothing
swatch.Reset()
MsgBox(finalSpeed / typingArea.Text.Length)
typingArea.Text = Nothing
logArea.Text = Nothing
Exit Sub
ElseIf typingArea.TextLength > 0 Then
'If the user has pressed anything other than return and there is already text in the typing area then do this
logArea.AppendText("time between two chars is " + temp.ToString() + Environment.NewLine)
finalSpeed += temp
temp = 0
swatch.Restart()
ElseIf typingArea.TextLength = 0 Then
'if there is nothing in the typing area then reset swatch
swatch.Restart()
End If
End Sub