简体   繁体   中英

Detect multiple Keyup / Keydown events and stop code firing on each C# / VB.Net

I have a DataGridView on WinForms where Column(0) shows a long list of dates.

On pressing the up or down arrows on a keyboard, the user changes the date selected and a keyup / keydown event is fired. This event calls a snippet of code that is quite demanding.

There is no issue with the keyup/keydown code that is fired and its subsequent call to 'CreateLeagueTable'

Private Sub DGVresults_KeyUp(sender As Object, e As KeyEventArgs) Handles DGVresults.KeyUp

    Dim col1 As Integer, row1 as integer
    Dim NewDate As String

    If e.KeyCode = Keys.Left OrElse e.KeyCode = Keys.Right Then
        Exit Sub
    End If

    col1 = DGVresults.CurrentCell.ColumnIndex
    row1 = DGVresults.CurrentCell.RowIndex

    If Not (col1 <> 0) Then

        NewDate = DGVresults.Rows(row1).Cells(0).Value

        Call CreateLeagueTable(NewDate)

    End If

End Sub

However, when the user presses the up / down arrow 'multiple times in quick sucession' the keyup / keydown event is also fired multiple times and I do not want this to occur.

How can I prevent the keyup/keydown event from firing multiple times and only occur on the last date the user has landed on?

Say the user presses the Down arrow 10 times quickly to get to the desired date. The KeyUp event is fired 10 times also and the user is left waiting whilst these 10 events occur. I only want the date of the last cell selected to go off and be fired.

Can you override a keyup/keydown sub with a new keyup/keydown pressed?

Thanks!

For the following code to work, you need a System.Windows.Forms.Timer called Timer1 (you can create one by dragging "Timer" onto your Form in the Forms Designer.

Whenever the current selection in the DataGridView changes, the timer is restarted with an interval of 2000 (2 seconds). When the timer ticks, the timer is stopped and your code is run.

Private Sub DGVresults_SelectionChanged(sender As Object, e As EventArgs) Handles DGVresults.SelectionChanged
    Timer1.Interval = 2000
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Timer1.Stop()
    Dim col1 As Integer = DataGridView1.CurrentCell.ColumnIndex
    Dim row1 As Integer = DataGridView1.CurrentCell.RowIndex

    If col1 = 0 Then CreateLeagueTable(CStr(DataGridView1.Rows(row1).Cells(0).Value))
End Sub

Sub CreateLeagueTable(dt As String)
    MessageBox.Show(dt) 'Your code replaces this
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM