Keydown event on a userform

J

Joe

Hi All,

I was trying to incorporate the keydown event to my userform. I
wanted to initiate the Closing when ESC button is pressed. The code
is given below.

'***********************************************************

Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger,
ByVal Shift As Integer)

If KeyCode = vbKeyEscape Then
Msgbox "Reached "
call C_Close_Click()
End If

End Sub

'***********************************************************


This works fine for a blank userform.
But when I have some other controls like Button or listbox, this is
not working. Can anyone help ?

Why it happens like that and How can avoid this problem

Mine is Excel 2003 SP2 / VB 6.3



Thanks

Joe
 
S

SeanC UK

Hi Joe,

Is it possible to add a Command Button to the form that can contain this
code? If so then you can change the Cancel property of the Command Button to
True and then pressing Escape will have the same effect as clicking this
Command Button and process your code.

You'll probably find that the reason it doesn't work when you add controls
to your form is because the controls have the focus, so the keydown event is
not occurring for the form, but for the control that has focus. Another way
to implement your code would be to write a keydown event for all the controls
that are able to take focus.

I hope this helps,

Sean.
 
J

Joe

Hi Joe,

Is it possible to add a Command Button to the form that can contain this
code? If so then you can change the Cancel property of the Command Button to
True and then pressing Escape will have the same effect as clicking this
Command Button and process your code.

You'll probably find that the reason it doesn't work when you add controls
to your form is because the controls have the focus, so the keydown event is
not occurring for the form, but for the control that has focus. Another way
to implement your code would be to write a keydown event for all the controls
that are able to take focus.

I hope this helps,

Sean.
--
(please remember to click yes if replies you receive are helpful to you)










- Show quoted text -

Thanks Sean....
It works. I already had a button for that as "C_Close" which I was
trying to call from there... Now I just have to modify that CANCEL
property to TRUE for that button.

I also saw that there is a DEFAULT property which you can assign to
the "OK" button... but that doesnt seem to work... let me try again..

Thanks again..
Joe
 

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