2

I have a MenuStrip in one of my forms so that the user has a menu bar they can choose various things from. For convenience, some also have key shortcuts mapped to them. I've also achieved a custom look for all the items and their submenus by overriding the MenuStrip's renderer.

The problem occurs when I use a key shortcut for an item with a dropdown list attached to it. When the list is down, if I hit the escape key, the list will close as expected, but the parent item is still selected. It's still highlighted, and it still has focus. Pressing the escape key again doesn't do anything. I take it that I'm suppose to implement this behavior myself? If so, how? ToolStripMenuItems don't seem to have any function calls that will tell it to unselect.

Edit: In case anyone is curious, I am looking capturing the escape key in the form's KeyDown event. I use it to quit the form. Here's the code:

Private Sub myForm_KeyDown(sender as Object, e As KeyEventArgs) Handles Me.KeyDown
   If e.KeyCode = Keys.Escape Then
      Me.Close()
      e.Handled = True
   End If
End Sub

But even when I comment this out, I'm still getting the above behavior.

MattM
  • 91
  • 1
  • 2
  • 10
  • Would you show us how you process the escape key (show your code). – Saeed Amiri Jul 18 '12 at 15:29
  • I'm not doing much. Inside the form's KeyDown event handler I have: 'If e.KeyCode = Keys.Escape Then' ' Me.Close()' ' e.Handled = True' 'End If' But even if I comment that out, I still get the above behavior. – MattM Jul 18 '12 at 16:30
  • 1
    OK update your answer with exact code, also is not bad to tag it as VB.net – Saeed Amiri Jul 18 '12 at 20:31

1 Answers1

1

By default, code placed in a form's KeyDown event will only trigger when the form itself has focus. In order to fire these events regardless of what has focus on the form, you must change the following property for the form:

KeyPreview from False to True.

This causes the form's "Key"-related events to trigger when the focus is on any control on the form.

Taylor K.
  • 1,077
  • 2
  • 14
  • 25
  • Sorry for the late reply, I had given up on this topic and moved on to other things. I already have the KeyPreview property set to true for some other things. – MattM Jul 30 '12 at 18:40
  • So, it still doesn't work with the KeyPreview set to True? Have you placed breaks to see if it triggers the myForm_KeyDown event when the parent item is selected? – Taylor K. Jul 30 '12 at 19:01