简体   繁体   English

C# 为什么我的控件在 KeyDown 事件中不接受多个键

[英]C# Why is my control not accepting multiple keys in the KeyDown event

Ok guys so I've been working on this control for close to a month and one of the issues that I'm having is that if I press the CTRL key by it's self it registers and if I press the Space key by it's self it registers.好的,我已经研究这个控件将近一个月了,我遇到的一个问题是,如果我按 CTRL 键,它会注册,如果我按 Space 键,它会自动注册寄存器。 I've tried to separate the two and I've tried to use them in the same if statement.我试图将两者分开,并尝试在同一个if语句中使用它们。 Both are unsuccessful.两者都不成功。

My first attempt was like this我的第一次尝试是这样的

protected override void OnKeyDown(KeyEventArgs e)
    {
        // base.OnKeyDown(e);
        if (_isEditing)
        {
            if (e.KeyData == Keys.Delete)
            {
                if (_selectedObj != null)
                {
                    DeleteSelectedObject();
                }
            }
        }
        if (e.Control && e.KeyData == Keys.Space)
        {
            _isEditing = !_isEditing;
            Invalidate();
        }
    }

Now if I remove the Ctrl or the 'Space' key from the equation it works fine.现在,如果我从等式中删除 Ctrl 或“空格”键,它可以正常工作。 So I tried to separate them and came up with所以我试着把它们分开并想出了

protected override void OnKeyDown(KeyEventArgs e)
    {
        // base.OnKeyDown(e);
        if (_isEditing)
        {
            if (e.KeyData == Keys.Delete)
            {
                if (_selectedObj != null)
                {
                    DeleteSelectedObject();
                }
            }
        }
        if (e.Control)
        {
            Console.WriteLine(DateTime.Now.ToShortTimeString());
            if (e.KeyData.Equals(Keys.Space))
            {
                _isEditing = !_isEditing;
                Console.WriteLine(DateTime.Now.Ticks.ToString());
            }
            Invalidate();
        }
    }

using the Console.WriteLine() as a cheater to tell me when the key is pressed and the Ticks doesn't get displayed unless I Comment out the CTRL clause.使用Console.WriteLine()作为骗子告诉我什么时候按下了键,除非我注释掉 CTRL 子句,否则不会显示刻度线。 Where am I going wrong here?我哪里出错了?

Try something like尝试类似的东西

if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Space)
{

}

You won't get modifier in a KeyDown event.您不会在 KeyDown 事件中获得修饰符。 Rather try one of the following ways to know if modifiers (Ctrl, Shift, Alt) are pressed or not:而是尝试以下方法之一来了解是否按下了修饰符(Ctrl、Shift、Alt):

  1. Keyboard.IsKeyDown

     if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) && e.KeyData == Keys.Space){}
  2. Check Keyboard.Modifiers检查Keyboard.Modifiers

     if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) && e.KeyData == Keys.Space){}

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

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