代码之家  ›  专栏  ›  技术社区  ›  Redbaron

C和箭头键

  •  20
  • Redbaron  · 技术社区  · 16 年前

    我刚接触C,正在现有应用程序中做一些工作。我有一个DirectX视区,其中包含我希望能够使用箭头键定位的组件。

    目前,我正在覆盖processCmdKey并捕获箭头输入并发送onkeypress事件。这是可行的,但我希望能够使用修饰符( 中高音 + CTRL + 换档 )只要我拿着一个修改器按下一个箭头,就不会触发我正在收听的任何事件。

    有人对我该去哪里有什么想法或建议吗?

    2 回复  |  直到 10 年前
        1
  •  11
  •   Brian R. Bondy    16 年前

    在重写的processCmdKey中,如何确定按下了哪个键?

    keydata(第二个参数)的值将根据按下的键和任何修改键而改变,因此,例如,按下左箭头将返回代码37,左移将返回65573,ctrl左131109和alt左262181。

    您可以使用适当的枚举值提取修改器和通过anding按下的键:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        bool shiftPressed = (keyData & Keys.Shift) != 0;
        Keys unmodifiedKey = (keyData & Keys.KeyCode);
    
        // rest of code goes here
    }
    
        2
  •  6
  •   Community kfsone    7 年前

    我投票赞成 Tokabi's answer ,但对于比较键,还有一些关于 StackOverflow.com here . 下面是一些我用来帮助简化一切的函数。

       public Keys UnmodifiedKey(Keys key)
        {
            return key & Keys.KeyCode;
        }
    
        public bool KeyPressed(Keys key, Keys test)
        {
            return UnmodifiedKey(key) == test;
        }
    
        public bool ModifierKeyPressed(Keys key, Keys test)
        {
            return (key & test) == test;
        }
    
        public bool ControlPressed(Keys key)
        {
            return ModifierKeyPressed(key, Keys.Control);
        }
    
        public bool AltPressed(Keys key)
        {
            return ModifierKeyPressed(key, Keys.Alt);
        }
    
        public bool ShiftPressed(Keys key)
        {
            return ModifierKeyPressed(key, Keys.Shift);
        }
    
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (KeyPressed(keyData, Keys.Left) && AltPressed(keyData))
            {
                int n = code.Text.IndexOfPrev('<', code.SelectionStart);
                if (n < 0) return false;
                if (ShiftPressed(keyData))
                {
                    code.ExpandSelectionLeftTo(n);
                }
                else
                {
                    code.SelectionStart = n;
                    code.SelectionLength = 0;
                }
                return true;
            }
            else if (KeyPressed(keyData, Keys.Right) && AltPressed(keyData))
            {
                if (ShiftPressed(keyData))
                {
                    int n = code.Text.IndexOf('>', code.SelectionEnd() + 1);
                    if (n < 0) return false;
                    code.ExpandSelectionRightTo(n + 1);
                }
                else
                {
                    int n = code.Text.IndexOf('<', code.SelectionStart + 1);
                    if (n < 0) return false;
                    code.SelectionStart = n;
                    code.SelectionLength = 0;
                }
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }