如何在 C# 中使用多个修饰键
我正在使用 keydown 事件来检测按下的按键,并有多个用于各种操作的组合键。
if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control && e.Modifiers == Keys.Shift)
{
//Do work
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
//Paste
}
由于某种原因,我按下 Ctrl + Shift + C 的组合键不起作用。我重新排序了它们,并将其放在顶部,认为可能是 Ctrl + C 的干扰,甚至删除了 Ctrl + C 查看它是否导致了问题。它仍然不起作用。我知道这可能很简单,但无法完全理解它是什么。我的所有 1 个修饰符 + 1 个组合键都工作正常,一旦我添加第二个修饰符,它就不再起作用。
I am using a keydown event to detect keys pressed and have several key combinations for various operations.
if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control && e.Modifiers == Keys.Shift)
{
//Do work
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
//Paste
}
For some reason the key combination in which I hit Ctrl + Shift + C is not working. I have re ordered them, and placed it at the top thinking it might be interference from the Ctrl + C, and even removed the Ctrl + C to see if it was causing a problem. It still does not work. I know it's probably something very simple, but can't quite grasp what it is. All of my 1 modifier + 1 key combination's work fine, as soon as I add a second modifier is when it no longer works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您是否尝试过
e.Modifiers == (Keys.Control | Keys.Shift)
?Have you tried
e.Modifiers == (Keys.Control | Keys.Shift)
?如果您想允许 Ctrl 和 Shift 则使用按位 OR (因为
Keys
是一个Flags
枚举)如果同时按下 Alt 也会失败
If you want to allow Ctrl and Shift then use the bitwise OR (as
Keys
is aFlags
enum)This will fail if Alt is pressed as well
另一种方法是添加一个不可见的菜单项,为其分配 Ctrl + Shift + C 快捷键,并在那里处理事件。
Another way would be to add an invisible menu item, assign the Ctrl + Shift + C shortcut to it, and handle the event there.
这就是我对 Ctrl+Z 撤消和 Ctrl+Shift+Z 所做的操作kbd> 重做操作,它起作用了。
This is what I did for a Ctrl+Z Undo and Ctrl+Shift+Z Redo operation and it worked.
试试这个。应该按照您想要的方式运行,而且更简单一些。
Try this. Should behave the way you want it to, and it's a little simpler.
鉴于没有其他人提到它们,我只是建议使用 KeyEventArgs.KeyData:
这应该只对特定的组合键起作用,尽管修饰符的顺序似乎并不重要,第一个总是最后按下的键。
e.Handled = true 应该阻止它,尽管我不知道它背后的具体机制。
Seeing as no one else mentions them, i'm just going to leave the suggestion to use KeyEventArgs.KeyData:
This should only act on specific key combinations, though the order of the modifiers don't seem to matter, the first one is always the last pressed key.
And e.Handled = true should stop it, though i don't know the specific mechanics behind it.
如果您有更多案例并且更易于阅读,另一种更合适的方法是:
Another approach more suitable if you have more cases, and easier to read is: