如何处理多个按键事件



我需要我的win form - vb.net,以检测是否Control + p被按下以及Control + Shift + p以及只是字母p被按下。

我已经准备好如何做到这一点,然后把它写进我的应用程序,但是我不能让它工作,所以我认为我做了一些根本性的错误。

我的代码
Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles DataGridView1.KeyUp, MyBase.KeyDown
If e.KeyCode = Keys.F9 Then
System.Diagnostics.Process.Start("calc.exe")
End If
If e.KeyCode = (Keys.P AndAlso Keys.ControlKey AndAlso Keys.ShiftKey) Then
If PrintBatchStickersToolStripMenuItem.Enabled = False Then Exit Sub
If DataGridView1.Rows.Count = 0 Then Exit Sub
Dim rowIndex As Integer = 0
rowIndex = DataGridView1.CurrentRow.Index
PrintAllMatchingProductCodeToolStripMenuItem_Click(sender, e)
ElseIf e.KeyCode = (Keys.P AndAlso Keys.ControlKey) Then
If PrintBatchStickersToolStripMenuItem.Enabled = False Then Exit Sub

If DataGridView1.Rows.Count = 0 Then Exit Sub
Dim rowIndex As Integer = 0
rowIndex = DataGridView1.CurrentRow.Index
PrintBatchQTYToolStripMenuItem_Click(sender, e)
ElseIf e.KeyCode = Keys.P Then
If PrintBatchStickersToolStripMenuItem.Enabled = False Then Exit Sub
If DataGridView1.Rows.Count = 0 Then Exit Sub
Dim rowIndex As Integer = 0
rowIndex = DataGridView1.CurrentRow.Index
PrintSingleStickerToolStripMenuItem_Click(sender, e)
End If
End Sub

如果我删除括号,我可以让它检测被按下的p键,但不能检测Control和Shift或它们的组合。

我将此添加到KeyUp事件中,因为从我的测试中可以看出,如果我在keydown上执行此操作,并且用户按住键,代码将反复循环打印贴纸的多个副本。我只需要代码执行一次。

按我所理解的键不能处理control键和shift键。

我的keyup错了吗,因为键可以在不同的时间被释放?如果我不能使用keyup,我怎么处理不打印多次keydown?

您需要使用KeyData而不是KeyCode,并且您需要正确组合Keys值:

Select Case e.KeyData
Case Key.P
'P was pressed without modifiers.
Case Keys.Control Or Key.P
'Ctrl+P was pressed without other modifiers.
Case Keys.Control Or Keys.Shift Or Keys.P
'Ctrl+Shift+P was pressed without other modifiers.
End Select

使用Or而不是And可能看起来很奇怪,但这是位操作,而不是布尔操作。如果您了解按位逻辑的工作原理(您应该了解),那么使用Or的原因就很明显了。

作为替代:

If e.KeyCode = Keys.P AndAlso Not e.Alt Then
If e.Control Then
If e.Shift Then
'Ctrl+Shift+P was pressed without other modifiers.
Else
'Ctrl+P was pressed without other modifiers.
End If
Else
'P was pressed without modifiers.
End If
End If

最新更新