Trapping the Enter Key

J

JamesJ

I want a form to open when a row is selected on a list box and the
Enter key is pressed but not sure how to trap the Enter key.

Any help will be appreciated,
James
 
R

Rick Brandt

JamesJ said:
I want a form to open when a row is selected on a list box and the
Enter key is pressed but not sure how to trap the Enter key.

Any help will be appreciated,
James

If you put a button on the form and set its Default property to Yes, then
its click event will be run when the Enter button is pressed. You can make
it small and transparent if you don't want the button visible.
 
S

Stuart McCall

JamesJ said:
I want a form to open when a row is selected on a list box and the
Enter key is pressed but not sure how to trap the Enter key.

Any help will be appreciated,
James

You can trap the enter key in the listbox's KeyPress event. Say your listbox
is called List1 and you have a DoubleClick event for it, and you want the
same code to execute when enter is pressed, then make the keypress event
look like this:

Private Sub List1_KeyPress(KeyAscii As Integer)
If KeyAscii = vbKeyReturn Then
KeyAscii = 0
List1_DblClick False
End If
End Sub
 
J

JamesJ

Thanks. I have a DoubleClick for the list box but wanted to have the same
action occur when I hit the Enter key.
I just needed to change your If statement line in your example to:

Private Sub lstDesc_KeyDown(KeyCode As Integer, Shift As Integer)

If KeyCode = vbReturn Then
'Code here
End If

End Sub

This seems to work fine.

Thanks,
James
 
S

Stuart McCall

JamesJ said:
Thanks. I have a DoubleClick for the list box but wanted to have the same
action occur when I hit the Enter key.
I just needed to change your If statement line in your example to:

Private Sub lstDesc_KeyDown(KeyCode As Integer, Shift As Integer)

If KeyCode = vbReturn Then
'Code here
End If

End Sub

This seems to work fine.

Thanks,
James

Yes it'll work, but it's due more to luck than management. The KeyCode
values that are delivered to the KeyDown event are very different to the
KeyAscii values in the KeyPress event. In KeyDown the codes represent the
electronic scan codes emitted by the keyboard's circuitry. In KeyPress the
codes represent the ASCII code of all the printable keys (and a few others).
It just so happens that KeyAscii vbReturn = 13 and KeyCode vbKeyReturn = 13.
Therefore I think your code ought to read either:

Private Sub lstDesc_KeyPress(KeyAscii As Integer)
If KeyAscii = vbKeyReturn Then
KeyAscii = 0
lstDesc_DblClick False
End If
End Sub

or:

Private Sub lstDesc_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyReturn Then
KeyCode = 0
lstDesc_DblClick False
End If
End Sub


Take your pick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top