tags:

views:

557

answers:

2

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.

Thank you

+1  A: 

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());
}
Wayne
+10  A: 

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" );
    }
Simon Wilson
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
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
Thank you very much, Simon. Works perfectly! I voted you up but where did the "Accept Answer" link go!
rp
I believe you should see a tick mark to click if you own the question?
Simon Wilson
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