PRB: Arrow Keys Do Not Always Produce a KeyDown Event (138530)
The information in this article applies to:
- Microsoft Visual Basic Standard Edition for Windows 4.0
- Microsoft Visual Basic Professional Edition for Windows 4.0
- Microsoft Visual Basic Enterprise Edition for Windows 4.0
- Microsoft Visual Basic Professional Edition for Windows 3.0
This article was previously published under Q138530 SYMPTOMS
The KeyDown event for a form is not invoked when using the arrow
(navigational) keys, even though the Keypreview property is set to True for
the form. Instead the arrow keys cause other controls to gain the focus,
even if the TabStop property is set to False for those controls.
NOTE: The DEL key may not trigger the KeyDown event either. For instance,
in Visual Basic 4.0 the DEL key in a masked edit box does not trigger the
KeyDown event.
RESOLUTION
You can get around this behavior by placing the problem controls onto a container that has a trappable KeyDown event. This would include the TabStrip, SSTab, PictureBox, and so forth. The following example uses a PictureBox because it is easily made unnoticeable.
Steps to Work Around Behavior- Create a new project in Visual Basic. Form1 is created by default.
- Set the KeyPreview property to True for Form1.
- Add a PictureBox to Form1 and set the following properties:
TabStop False
BorderStyle 0 - None
BackColor Same as From (by default)
- Add three CommandButtons to Picture1.
- Set the Tabstop property of each CommandButton to False.
- Add the following code to the code window of Form1:
Private Sub Command5_Click()
'some code here
Picture1.SetFocus
End Sub
Private Sub Command6_Click()
'some code here
Picture1.SetFocus
End Sub
Private Sub Command7_Click()
'some code here
Picture1.SetFocus
End Sub
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Debug.Print "Form_KeyDown - " & KeyCode
End Sub
Private Sub Picture1_KeyDown(KeyCode As Integer, Shift As Integer)
Debug.Print "Picture1_KeyDown - " & KeyCode
End Sub
- Run the program by pressing the F5 key. Note that the PictureBox is unnoticeable.
Pressing an arrow key activates the KeyDown event of the PictureBox and of the form.
You can now use either Event to trap the Arrow keys.
STATUS
Microsoft is researching this behavior and will post new information here
in the Microsoft Knowledge Base as it becomes available.
Modification Type: | Minor | Last Reviewed: | 3/14/2005 |
---|
Keywords: | kbprb KB138530 |
---|
|