Test if the Ctrl key is down using C#

C#Winforms

C# Problem Overview


I have a form that the user can double click on with the mouse and it will do something. Now I want to be able to know if the user is also holding the Ctrl key down as the user double click on the form.

How can I tell if the user is holding the Ctrl key down?

C# Solutions


Solution 1 - C#

Using .NET 4 you can use something as simple as:

    private void Control_DoubleClick(object sender, EventArgs e)
    {
        if (ModifierKeys.HasFlag(Keys.Control))
        {
            MessageBox.Show("Ctrl is pressed!");
        }
    }

If you're not using .NET 4, then the availability of Enum.HasFlag is revoked, but to achieve the same result in previous versions:

    private void CustomFormControl_DoubleClick(object sender, EventArgs e)
    {
        if ((ModifierKeys & Keys.Control) == Keys.Control)
        {
            MessageBox.Show("Ctrl is pressed!");
        }
    }

Solution 2 - C#

Just for completeness... ModifierKeys is a static property of Control, so you can test it even when you are not directly in an event handler:

public static bool IsControlDown()
{
    return (Control.ModifierKeys & Keys.Control) == Keys.Control;
}

Solution 3 - C#

This isn't really an answer to the question at hand, but I needed to do this in a console application and the detail was a little different.

I had to add references to WindowsBase and PresentationFramework, and at that point I could do:

if (System.Windows.Input.Keyboard.Modifiers == ModifierKeys.Control)
   blah

Just adding this here in case someone else is doing something similar.

Solution 4 - C#

Even this also

 private void Control_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (ModifierKeys == Keys.Control)
            MessageBox.Show("with CTRL");
    }

Solution 5 - C#

This works for me:

 if(Keyboard.IsKeyDown(Key.LeftCtrl))
    {}

And add references to PresentationCore and WindowsBase

Solution 6 - C#

The same soneone said above, but comparing as different than zero, which should be a little faster and use less instructions on most architectures:

public static bool IsControlDown()
{
    return (Control.ModifierKeys & Keys.Control) != 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionItay.BView Question on Stackoverflow
Solution 1 - C#Grant ThomasView Answer on Stackoverflow
Solution 2 - C#RobView Answer on Stackoverflow
Solution 3 - C#Chris RaeView Answer on Stackoverflow
Solution 4 - C#Javed AkramView Answer on Stackoverflow
Solution 5 - C#bar-techView Answer on Stackoverflow
Solution 6 - C#user1489240View Answer on Stackoverflow