C#和方向键
时间:2020-03-05 18:38:21 来源:igfitidea点击:
我是Cand的新手,我正在现有的应用程序中做一些工作。我有一个DirectX视口,其中包含要使用箭头键定位的组件。
目前,我正在重写ProcessCmdKey并捕获箭头输入并发送OnKeyPress事件。这行得通,但是我希望能够使用修饰符(ALT
+CTRL
+SHIFT
)。按住修饰符并按箭头后,不会触发我正在听的任何事件。
有人对我应该去哪里有任何想法或者建议吗?
解决方案
回答
在覆盖的ProcessCmdKey中,如何确定已按下哪个键?
keyData(第二个参数)的值将根据所按下的键和任何修改键而变化,例如,按向左箭头将返回代码37,向左移将返回65573,向左按Ctrl键返回131109,向左按alt键262181.
我们可以使用适当的枚举值来提取修饰符和"与"运算所按下的键:
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 }
回答
我对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); }