定时器没有停止?

时间:2015-04-11 01:15:51

标签: vb.net visual-studio-2008 timer

我有一个计时器,在5秒后将文本框文本设置为vbnullstring,这是为了防止用户输入,因为他们要做的是扫描条形码,现在读完条形码后,扫描仪将做一个回车键,所以我有这个代码

'TextBox Keypress event
Timer1.Start()

'TextBox keydown event
If e.KeyCode = Keys.Enter Then
   Timer1.Stop()
   Timer1.Dispose() 'Tried adding this but still doesn't work
End if

我的代码上没有任何内容会导致按键事件再次触发,但即使按下输入文本框上的关键字仍然会被删除。

2 个答案:

答案 0 :(得分:1)

  

一个计时器,在5秒后将文本框文本设置为vbnullstring,这是为了防止用户输入

为什么不将控件设置为只读模式?

<强> TextBox.ReadOnly Property - MSDN - Microsoft

我将逻辑移动到自定义用户控件:

''' <summary>
''' Class TextBoxEx.
''' </summary>
Public NotInheritable Class TextBoxEx : Inherits TextBox

''' <summary>
''' The delay Timer.
''' </summary>
Private WithEvents tmrDelay As Timer

''' <summary>
''' Initializes a new instance of the <see cref="TextBoxEx"/> class.
''' </summary>
Public Sub New()
    Me.tmrDelay = New Timer
End Sub

''' <summary>
''' Puts the control in ReadOnly state after the specified delay interval.
''' </summary>
''' <param name="delay">The delay, in milliseconds.</param>
Public Sub SetDelayedReadonly(ByVal delay As Integer)

    With Me.tmrDelay
        .Interval = delay
        .Enabled = True
        .Start()
    End With

End Sub

''' <summary>
''' Handles the Tick event of the <see cref="tmrDelay"/> instance.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) _
Handles tmrDelay.Tick

    MyBase.ReadOnly = True

    With Me.tmrDelay
        .Stop()
        .Enabled = False
    End With

End Sub

End Class

然后,使用它:

Private Sub TextBoxEx1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) _
Handles TextBoxEx1.KeyDown

    If e.KeyCode = Keys.Enter Then
        DirectCast(sender, TextBoxEx).SetDelayedReadonly(delay:=5000)
    End If

End Sub

编辑:代码已更新,我理解错误的目的。

答案 1 :(得分:0)

我在你的代码中看到了一些问题

首先,按以下顺序触发关键事件
KeyDown
KeyPress
KeyUp

这意味着在第一次启动计时器后,计时器将永远不会因为您在KeyDown事件中停止计时器而结束,之后您将在{{1}中再次启动计时器事件。

其次,您正在启动计时器而不检查计时器是否已停止。

如果你想在按下任何键时启动计时器,你可以在KeyPress事件中使用此代码

KeyDown

希望这有帮助。