Wednesday, May 21, 2008

Detect the Shift, Ctrl, Return Key pressed at the same time

Another simple one.  I needed to detect if the Shift, Ctrl, and Return key were pressed at the same time.  Now, the three combinations, could consist of the Alt key as well.  Anyways, for some reason I just wasn't getting it, even though I knew it was a simple problem.  This is my solution.  If you were to debug this.  Just open a new Windows Application project and paste this in.  The key thing if you were to debug this is to put the breakpoint on the Debug line.  If you put the breakpoint on the Select Case statement (which I was doing and which was messing me up), it will appear that its not working.  Basically the reason is that if you press the Shift, Ctrl, and Return key, the first time through the Routine it will detect the Shift, or Ctrl keys, and it won't go into your if statement.  However, after it goes through those checks, it will evaluate the Return key that was pressed.  Now, when the return key is pressed you check if the Shift and Control keys are also down through the statement e.Shift and e.Control.  This returns true and you are set.

  Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    Select Case e.KeyCode
      Case Keys.Enter
        If e.Shift And e.Control Then
          Debug.Write("all three pressed")
        End If
    End Select
  End Sub

The MSDN documentation has an example where you use the e.Modifiers value, and to be honest at this point I am not sure how that value gets set.  But the above procedure does work.

-- Ted

No comments: