I am trying to detect the keys "Control" and "t" being pressed simultaneously in VB.NET. The code I have so far is as follows:
Private Sub frmTimingP2P_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyValue = Keys.ControlKey And e.KeyValue = Keys.T Then
MessageBox.Show("Ctrl + T")
End If
End Sub
I can detect one key or the other by removing the and statement and the second keyvalue statement, but I don't really get anything when I try this. Is there another method?
Thanks
Private Sub frmMain_Zaporka_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
End Sub
I dont have vb.net installed right now but try this on your keydown or keypress event:
I'll save you from the long code. Here:
I had the same problem, but for me to get this to work I had to set the forms KeyPreview property to true. In Visual studio you can change this in the Forms [Design] Property window or changing the property on load.
then use by using:
or other program logic as provided in the answers above.
First of all,
And
in your code should beAndAlso
since it’s a logical operator.And
in VB is a bit operator. Next, you can use theModifiers
property to test for modifier keys:The
e.KeyCode And Not Keys.Modifiers
in the first part of the condition is necessary to mask out the modifier key.If e.Modifiers = Keys.Ctrl
can also be written asIf e.Control
.Alternatively, we can collate these two queries by asking directly whether the combination Ctrl+T was pressed:
In both snippets we make use of bit masks.