Edit

Share via


How to: Determine Which Modifier Key Was Pressed

When you create an application that accepts the user's keystrokes, you may also want to monitor for modifier keys such as the SHIFT, ALT, and CTRL keys. When a modifier key is pressed in combination with other keys, or with mouse clicks, your application can respond appropriately. For example, if the letter S is pressed, this may simply cause an "s" to appear on the screen, but if the keys CTRL+S are pressed, the current document may be saved. If you handle the KeyDown event, the Modifiers property of the KeyEventArgs received by the event handler specifies which modifier keys are pressed. Alternatively, the KeyData property of KeyEventArgs specifies the character that was pressed as well as any modifier keys combined with a bitwise OR. However, if you are handling the KeyPress event or a mouse event, the event handler does not receive this information. In this case, you must use the ModifierKeys property of the Control class. In either case, you must perform a bitwise AND of the appropriate Keys value and the value you are testing. The Keys enumeration offers variations of each modifier key, so it is important that you perform the bitwise AND with the correct value. For example, the SHIFT key is represented by Shift, ShiftKey, RShiftKey and LShiftKey The correct value to test SHIFT as a modifier key is Shift. Similarly, to test for CTRL and ALT as modifiers you should use the Control and Alt values, respectively.

Note

Visual Basic programmers can also access key information through the Keyboard property

To determine which modifier key was pressed

  • Use the bitwise AND operator with the ModifierKeys property and a value of the Keys enumeration to determine whether a particular modifier key is pressed. The following code example shows how to determine whether the SHIFT key is pressed within a KeyPress event handler.

    private:
        void textBox1_KeyPress(Object^ sender, KeyPressEventArgs^ e)
        {
            if ((Control::ModifierKeys & Keys::Shift) == Keys::Shift)
            {
                MessageBox::Show("Pressed " + Keys::Shift.ToString());
            }
        }
    
    public void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
        {
            MessageBox.Show("Pressed " + Keys.Shift);
        }
    }
    
    Public Sub TextBox1_KeyPress(ByVal sender As Object, _
        ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
    
        If ((Control.ModifierKeys And Keys.Shift) = Keys.Shift) Then
            MsgBox("Pressed " + Keys.Shift.ToString())
        End If
    End Sub
    

See also