Control KeyDown Event Trap CTRL-C etc

2019-08-29 08:29发布

问题:

I'm having a problem with processing CTRL-C, CTRL-V, CTRL-X on my form.

Private Function HandleKeyDown(sender As Object,
                                   e As KeyEventArgs,
                                   ByVal vShow As String) As Boolean
        HandleKeyDown = False
        If e.KeyCode = Keys.F1 Then
            Help.ShowPopup(Me, vShow, Cursor.Position)
        End If
        If e.KeyCode = Keys.C AndAlso e.Modifiers = Keys.Control Then
            sender.Copy()
        ElseIf e.KeyCode = Keys.V AndAlso e.Modifiers = Keys.Control Then
            sender.Paste()
        ElseIf e.KeyCode = Keys.X AndAlso e.Modifiers = Keys.Control Then
            sender.Cut()
        Else
            Console.WriteLine(String.Format("Modifiers:{0} KeyCode:{1} KeyData:{2} KeyValue:{3} ", e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
        End If
        HandleKeyDown = True
    End Function

The KeyDown event never picks up the second key. The only value the KeyCode ever seems to hold is Keys.Control. This is what the Console.WriteLine outputs for CTRL-C

Modifiers:Control KeyCode:ControlKey KeyData:ControlKey, Control KeyValue:17 

Where am I going wrong?

回答1:

Are you calling this from the actual event handler? I had to add "Handles MyBase.KeyDown" and remove your extra parameter.

Private Sub HandleKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown
    'HandleKeyDown = False

    If e.KeyCode = Keys.C AndAlso e.Modifiers = Keys.Control Then
        MessageBox.Show(String.Format("Modifiers:{0} --- KeyCode:{1}  --- KeyData:{2}  --- KeyValue:{3} ",
                                      e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
        'sender.Copy()
    ElseIf e.KeyCode = Keys.V AndAlso e.Modifiers = Keys.Control Then
        MessageBox.Show(String.Format("Modifiers:{0}  --- KeyCode:{1}  --- KeyData:{2}  --- KeyValue:{3} ",
                                      e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
        'sender.Paste()
    ElseIf e.KeyCode = Keys.X AndAlso e.Modifiers = Keys.Control Then
        MessageBox.Show(String.Format("Modifiers:{0}  --- KeyCode:{1}  --- KeyData:{2}  --- KeyValue:{3} ",
                                      e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
        'sender.Cut()
    End If

    'HandleKeyDown = True
End Sub

It's working for me. I get a value of 88, 67, and 86 respectively.