TheRunner83
TheRunner83

Reputation: 41

Adding event handlers to object

Is there a way to add keydown and keyleft event handler to image object in a user form? I can only see mouseup/down/move,error,dragover,dropandpaste.

I notice with an option button, the event keydown/keyleft is available but not for image. Thanks in advance

Upvotes: 2

Views: 314

Answers (2)

gembird
gembird

Reputation: 14053

It depends on what are you trying to achieve which you didn't specify.

Image obviously doesn't have Key-events so it can't be used directly. One possible solution could be to use Frame control which has a Picture property and has KeyDown event, so you can catch key-downs when the frame has focus. Example:

Private Sub FrameWithPicture_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    ' Compare KeyCode with predefined vbKey-Constansts, e.g. for key-left:
    If KeyCode = vbKeyLeft Then
        ' left arrow key was pressed, do somthing
    Else
        ' all other keys were pressed, do something else 
    End If
End Sub

Or you could add Image control to this frame and when key-down event occurs on the frame, then perform some action on this image like this: FrameWithImage.Controls.Item(0).BackColor = vbRed etc. HTH

Upvotes: 2

ThunderFrame
ThunderFrame

Reputation: 9471

You can't add event handlers that don't exist for that control type (other than by subclassing, but the image control doesn't receive focus anyway), but an image control can't receive the focus, and therefore can't receive keystrokes anyway.

You talk about KeyDown and KeyLeft events. While some controls have KeyDown, KeyPress and KeyUp events, there aren't any controls that have a KeyLeft event. Do you perhaps mean to capture the KeyDown event, and then detect whether the Down arrow or Left arrow was the key that pressed down?

However, there are a few options:

  1. Wire up the KeyDown or KeyPress event (depending upon which type of key information you require) for the UserForm, and then act upon the image control. This is probably only of use if you're happy for keypresses to be handled by the form, regardless of which other control might be selected.

  2. Add a proxy control, say a TextBox that does receive KeyDown and KeyPress events, and place it behind the image control. That way, when the user tabs to the textbox, you can add a border to the image to make it look like it is selected, and then have the textbox key events act upon the image. If a user clicks on the image, instead of tabbing between controls, you can set the image's click event to give the textbox the focus, and again, handle the key events for the textbox as a proxy for the image control.

Upvotes: 3

Related Questions