问题描述
我需要我的 win 表单 - 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 上执行此操作,并且用户按住这些键,则代码将一遍又一遍地循环打印贴纸的多个副本。我需要代码只执行一次。
根据我的理解,按键无法处理我能理解的控制和移位键。
我的键盘设置有问题吗,因为键可能会在不同的时间被释放?如果我不能使用 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