How to use multiple modifier keys in C#

2019-01-09 11:38发布

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.

8条回答
Evening l夕情丶
2楼-- · 2019-01-09 12:20

Another way would be to add an invisible menu item, assign the Ctrl + Shift + C shortcut to it, and handle the event there.

查看更多
Viruses.
3楼-- · 2019-01-09 12:22

Seeing as no one else mentions them, i'm just going to leave the suggestion to use KeyEventArgs.KeyData:

if (e.KeyData == (Keys.C | Keys.Control | Keys.Shift)
{
  //do stuff
  //potentially use e.Handled = true
}
if (e.KeyData == (Keys.V | Keys.Control)
{
  //do other stuff
  //potentially use e.Handled = true
}

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.

查看更多
疯言疯语
4楼-- · 2019-01-09 12:25

This is what I did for a Ctrl+Z Undo and Ctrl+Shift+Z Redo operation and it worked.

  Private Sub Form_Main_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
    Select Case e.KeyCode
      Case Keys.Add
        diagramView.ZoomIn()
      Case Keys.Subtract
        diagramView.ZoomOut()
      Case Keys.Z
        If e.Modifiers = Keys.Control + Keys.Shift Then
          diagram.UndoManager.Redo()
        ElseIf e.Modifiers = Keys.Control Then
          diagram.UndoManager.Undo()
        End If
    End Select
  End Sub
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-09 12:29

Have you tried e.Modifiers == (Keys.Control | Keys.Shift)?

查看更多
在下西门庆
6楼-- · 2019-01-09 12:32
if (e.KeyCode == Keys.C && e.Modifiers == (Keys.Control | Keys.Shift))
{
    //Do work
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
    //Paste
}
查看更多
迷人小祖宗
7楼-- · 2019-01-09 12:32
      if ((Keyboard.Modifiers & ModifierKeys.Shift | ModifierKeys.Control) > 0)
          Debugger.Launch();
查看更多
登录 后发表回答