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

前端 未结 5 615
甜味超标
甜味超标 2021-01-02 03:34

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_K         


        
5条回答
  •  天涯浪人
    2021-01-02 03:45

    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.Ctrl 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.

提交回复
热议问题