简体   繁体   English

使用C#测试Ctrl键是否已关闭

[英]Test if the Ctrl key is down using C#

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. 现在我希望能够知道当用户双击表单时用户是否也按住Ctrl键。

How can I tell if the user is holding the Ctrl key down? 如何判断用户是否按住Ctrl键?

Using .NET 4 you can use something as simple as: 使用.NET 4,您可以使用以下简单的内容:

    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: 如果您不使用.NET 4,则会撤消Enum.HasFlag的可用性,但要在以前的版本中获得相同的结果:

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

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: 为了完整性...... ModifierKeysControl的静态属性,因此即使您不是直接在事件处理程序中,也可以测试它:

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

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: 我必须添加对WindowsBasePresentationFramework引用,此时我可以这样做:

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

Just adding this here in case someone else is doing something similar. 只是在这里添加这个,以防其他人正在做类似的事情。

Even this also 即便如此

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

The same soneone said above, but comparing as different than zero, which should be a little faster and use less instructions on most architectures: 上面说的是同一个soneone,但是比较不同于零,这应该更快一点并且在大多数架构上使用更少的指令:

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

This works for me: 这对我有用:

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

And add references to PresentationCore and WindowsBase 并添加对PresentationCore和WindowsBase的引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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