14

How can I determine when the control key is held down during button click in a C# Windows program? I want one action to take place for Ctrl/Click and a different one for Click.

Drahakar
  • 5,986
  • 6
  • 43
  • 58
rp.
  • 17,483
  • 12
  • 63
  • 79

2 Answers2

31

And a little bit more:

private void button1_Click ( object sender, EventArgs e )
{           
    if( (ModifierKeys  & Keys.Control) == Keys.Control )
    {
        ControlClickMethod();    
    }
    else
    {
        ClickMethod();
    }
}

private void ControlClickMethod()
{
    MessageBox.Show( "Control is pressed" );
}

private void ClickMethod()
{
    MessageBox.Show ( "Control is not pressed" );
}
joce
  • 9,624
  • 19
  • 56
  • 74
Simon Wilson
  • 9,929
  • 3
  • 27
  • 24
  • I feel really stupid. I had no idea that ModifierKeys existed. I've been doing it old school (capturing the keydown and setting a boolean) for years. I guess you do learn something new every day. :) – John Kraft Dec 09 '08 at 19:05
  • 3
    I feel "stupid" everyday...and definitely every time I come on StackOverflow, then I get inspired by the "smart" developers and strife to better myself. (This is in no way an agreement with you being "stupid" by the way") – Simon Wilson Dec 09 '08 at 19:08
  • Thank you very much, Simon. Works perfectly! I voted you up but where did the "Accept Answer" link go! – rp. Dec 09 '08 at 19:18
  • I believe you should see a tick mark to click if you own the question? – Simon Wilson Dec 09 '08 at 19:25
  • Got it. Thank you again, very much. I googled the crap out of this and then you answered me in a matter of minutes. I appreciate it. – rp. Dec 09 '08 at 20:14
5

Assuming WinForms, use Control.ModifierKeys, eg:

private void button1_Click(object sender, EventArgs e) {
    MessageBox.Show(Control.ModifierKeys.ToString());
}

Assuming WPF, use Keyboard.Modifiers, eg:

private void Button_Click(object sender, RoutedEventArgs e) {
    MessageBox.Show(Keyboard.Modifiers.ToString());
}
lesscode
  • 6,221
  • 30
  • 58