Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect simultaneous keypresses such as "Ctrl + T" in VB.NET?

Tags:

vb.net

keydown

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

like image 541
J2Tuner Avatar asked Dec 10 '12 15:12

J2Tuner


2 Answers

I'll save you from the long code. Here:

If e.Control And e.Alt And e.KeyCode = Keys.G Then
    MsgBox("Control Alt G")
End If
like image 67
Gerard Balaoro Avatar answered Oct 26 '22 08:10

Gerard Balaoro


First of all, And in your code should be AndAlso since it’s a logical operator. And in VB is a bit operator. Next, you can use the Modifiers property to test for modifier keys:

If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
    MessageBox.Show("Ctrl + T")
End If

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 as If e.Control.

Alternatively, we can collate these two queries by asking directly whether the combination Ctrl+T was pressed:

If e.KeyCode = (Keys.T Or Keys.Ctrl) Then …

In both snippets we make use of bit masks.

like image 30
Konrad Rudolph Avatar answered Oct 26 '22 06:10

Konrad Rudolph