Export (0) Print
Expand All

Determining Which Modifier Key Was Pressed

Visual Studio .NET 2003

When creating 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 — the letter S may simply cause an "S" to appear on the screen, but if CTRL+S is pressed, the current document may be saved.

To determine which modifier key was pressed

  • Use the bitwise AND operator (And in Visual Basic, & in C# and C++) with the ModifierKeys property and a value of the Keys enumeration to determine which modifier key was pressed. (ModifierKeys is a shared member of the Control class; for more information on shared members, see Shared Members.)
    ' Visual Basic
    Private Sub Button1_KeyPress(ByVal sender As Object, ByVal e As _
    System.Windows.Forms.KeyPressEventArgs) Handles Button1.KeyPress
       If (Control.ModifierKeys And Keys.Shift) = Keys.Shift Then
          MessageBox.Show("Pressed " & Keys.Shift)
       End If
    End Sub
    
    // C#
    private void button1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) 
    {
       if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) 
       {
         MessageBox.Show("Pressed " + Keys.Shift);
       }
    }
    
    // C++
    private:
       System::Void button1_KeyPress(System::Object *  sender,
          System::Windows::Forms::KeyPressEventArgs *  e)
       {
          if ((Control::ModifierKeys & Keys::Shift) == Keys::Shift)
          {
             MessageBox::Show(String::Concat(S"Pressed ",
                __box(Keys::Shift)->ToString()));
          }
       }
    
    Note   For C# or C++, be sure that the necessary code to enable the event handler is present. In this case, it would be similar to the following:
    // C#
    this.button1.Click += new System.EventHandler(this.button1_Click);
    
    // C++
    this->button1->add_KeyPress
       (new System::Windows::Forms::KeyPressEventHandler
       (this, button1_KeyPress));
    

See Also

Keys Enumeration | Control.ModifierKeys Property

Show:
© 2014 Microsoft