Search code examples
vbaexcelevent-handlinguserform

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


Solution

  • 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.