Edit

Share via


How to check for modifier key presses (Windows Forms .NET)

As the user types keys into your application, you can monitor for pressed modifier keys such as the SHIFT, ALT, and CTRL. When a modifier key is pressed in combination with other keys or even a mouse click, your application can respond appropriately. For example, pressing the S key may cause an "s" to appear on the screen. If the keys CTRL+S are pressed, instead, the current document may be saved.

If you handle the KeyDown event, the KeyEventArgs.Modifiers property received by the event handler specifies which modifier keys are pressed. Also, the KeyEventArgs.KeyData property specifies the character that was pressed along with any modifier keys combined with a bitwise OR.

If you're handling the KeyPress event or a mouse event, the event handler doesn't receive this information. Use the ModifierKeys property of the Control class to detect a key modifier. In either case, you must perform a bitwise AND of the appropriate Keys value and the value you're testing. The Keys enumeration offers variations of each modifier key, so it's important that you do the bitwise AND check with the correct value.

For example, the SHIFT key is represented by the following key values:

The correct value to test SHIFT as a modifier key is Keys.Shift. Similarly, to test for CTRL and ALT as modifiers you should use the Keys.Control and Keys.Alt values, respectively.

Detect modifier key

Detect if a modifier key is pressed by comparing the ModifierKeys property and the Keys enumeration value with a bitwise AND operator.

The following code example shows how to determine whether the SHIFT key is pressed within the KeyPress and KeyDown event handlers.

// Event only raised when non-modifier key is pressed
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
        MessageBox.Show("KeyPress " + Keys.Shift);
}

// Event raised as soon as shift is pressed
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
        MessageBox.Show("KeyDown " + Keys.Shift);
}
' Event only raised when non-modifier key is pressed
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
    If ((Control.ModifierKeys And Keys.Shift) = Keys.Shift) Then
        MessageBox.Show("KeyPress " & [Enum].GetName(GetType(Keys), Keys.Shift))
    End If
End Sub

' Event raised as soon as shift is pressed
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs)
    If ((Control.ModifierKeys And Keys.Shift) = Keys.Shift) Then
        MessageBox.Show("KeyPress " & [Enum].GetName(GetType(Keys), Keys.Shift))
    End If
End Sub

See also