按右箭头导致向上箭头被设置
我在这样的控件中重写 ProcessCmdKey
:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if ((keyData & Keys.Up) == Keys.Up)
MessageBox.Show("Up arrow");
else if ((keyData & Keys.Right) == Keys.Right)
MessageBox.Show("Right arrow");
// it doesn't matter what I return, the glitch happens anyway
return base.ProcessCmdKey(ref msg, keyData);
}
当我按向上箭头键时,会出现消息向上箭头
,但当我按向右箭头键时也会出现该消息。这是为什么呢?
I am overriding ProcessCmdKey
in a control like this:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if ((keyData & Keys.Up) == Keys.Up)
MessageBox.Show("Up arrow");
else if ((keyData & Keys.Right) == Keys.Right)
MessageBox.Show("Right arrow");
// it doesn't matter what I return, the glitch happens anyway
return base.ProcessCmdKey(ref msg, keyData);
}
And when I press the Up arrow key, the message Up arrow
appears, but it also appears when I press the Right arrow key. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案非常简单
Keys.Right
的值为 39,Keys.Up
的值为 38。您的第一位和操作是 38 或 39 & 39。 38 始终是 38,那么您要检查 38 是否等于 38(始终为真)。The answer is realy simple
Keys.Right
has value 39 andKeys.Up
has value 38. Your first bit and operation is 38 or 39 & 38 which is always 38, then you're cheking if 38 is equal to 38 which is always true.阅读上面的评论以获取问题的描述。
您甚至不需要强制转换它,因为参数是作为键传入的。因此,您可以像比较两个字符串或整数一样比较两个枚举。
Read the comment above for a description of the problem.
You don't even need to cast it, because the argument is passed in as a key. So you can compare the two enums just like you would two strings or integers.
事实上,问题在于 (int)key 值不是 2 的幂。只要您只想捕获单个击键,您就可以使用 (keys == Keys.Up) 或其他。
当您还想捕获 Control 或 Shift 键时,通过 (keyData == ((Keys)(Keys.Shift | Keys.Up))) 这是不可能的
我使用的解决方案可能不是最复杂的,但我不能在此类项目上浪费大量时间。这种方法至少有效:
indeed the problem is that the (int)key values are not powers of 2. As long as you only want to capture single keystrokes, you can just use (keys == Keys.Up) or whatever.
When you want to catch control or shift keys as well, this is not possible via (keyData == ((Keys)(Keys.Shift | Keys.Up)))
The solution i used is maybe not the most sophisticated, but I can't spoil a lot of time on this kind of items. This approach at least works: