简体   繁体   中英

Test for 'Ctrl' keydown in C#

如何在Windows Forms / C#中测试Ctrl down?

bool ctrl = ((Control.ModifierKeys & Keys.Control) == Keys.Control);

If you want to detect in a Key press handler, you would look at the modifier properties:

private void button1_KeyPress(object sender, 
                              System.Windows.Forms.KeyPressEventArgs e) 
{
   if ((Control.ModifierKeys & Keys.Control) == Keys.Control) 
   {
     MessageBox.Show("Pressed " + Keys.Control);
   }
}

Actually, looking at that and seeing it doesn't use the e argument, it seems as long as your "this" is derived from a Form or Control then you can make this call at any time and not just in a keyboard event handler.

However, if you wanted to ensure a combination, such as Ctrl - A was pressed, you would need some additional logic.

private void myKeyPress(object sender, 
                        System.Windows.Forms.KeyPressEventArgs e) 
{
   if (((Control.ModifierKeys & Keys.Control) == Keys.Control) 
        && e.KeyChar == 'A')
   {
     SelectAll();
   }
}

Adding a late answer to an old question...

The other answers read the current state of the control key. If you want to directly read the control flag from the passed event args (ie as it was at the time that the event occurred), use either the KeyUp or KeyDown events (not KeyPress ):

private void HandleTextKeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.A)
    {
        ((TextBox)sender).SelectAll();
        e.Handled = true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM