tags:

views:

175

answers:

2

Hi, How do I test for 'Ctrl' downdown in winforms/c#?

+5  A: 
bool ctrl = ((Control.ModifierKeys & Keys.Control) == Keys.Control);
Marc Gravell
+4  A: 

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();
   }
}
Ray Hayes