How to use multiple modifier keys in C#

陌路散爱 提交于 2019-11-27 09:12:03
if (e.KeyCode == Keys.C && e.Modifiers == (Keys.Control | Keys.Shift))
{
    //Do work
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
    //Paste
}
Chris J

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

JDunkerley

If you want to allow Ctrl and Shift then use the bitwise OR (as Keys is a Flags enum)

if (e.KeyCode == Keys.C && e.Modifiers == (Keys.Control | Keys.Shift))
{
    //Do work (if Ctrl-Shift-C is pressed, but not if Alt is pressed as well)
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
    //Paste (if Ctrl is only modifier pressed)
}

This will fail if Alt is pressed as well

Druid

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

      if ((Keyboard.Modifiers & ModifierKeys.Shift | ModifierKeys.Control) > 0)
          Debugger.Launch();

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

Try this. Should behave the way you want it to, and it's a little simpler.

 if (e.Control)
 {
    if (e.Shift && e.KeyCode == Keys.C)
    {
       //Do work
    }
    else if (e.KeyCode == Keys.V)
    {
       //Paste
    }
 }

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!