C#和箭头键

26

我刚开始接触C#,正在对一个现有应用程序进行一些工作。我有一个带有组件的DirectX视口,想使用箭头键来定位这些组件。

目前我正在覆盖ProcessCmdKey方法并捕获箭头输入,然后发送OnKeyPress事件。这个方法是有效的,但我想能够使用修饰符(ALT+CTRL+SHIFT)。只要我按住修饰键并按箭头键,我监听到的事件就不会被触发。

有没有人有任何想法或建议,该怎么做呢?

2个回答

13

在您覆盖的ProcessCmdKey方法中,您如何确定按下了哪个键?

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

您可以通过与适当的枚举值进行AND操作来提取修改器和按下的键:

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
}

6

我赞同了Tokabi的答案,但是如果要比较键值,则有一些额外的建议在StackOverflow.com这里。以下是我使用的一些函数,以帮助简化所有内容。

   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);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接