hotkey in usrform

X

x taol

I want to focus the specific control in that userform if press the F3
key.
Current, the userform have many controls.

in that case, even if any control has focus, i want to be focused the
specific control(combobox or textbox, etc) of the userform when the F3
key pressed.



*** Sent via Developersdex http://www.developersdex.com ***
 
M

Michel Pierron

Hi x taol,
You can do that by subclassing your UserForm (do not forget to take all the
precautions of use relating to the use of this method). By way of example:

In a standard module:
Option Explicit
Private Declare Function RegisterHotKey& Lib "user32" _
(ByVal hWnd&, ByVal id&, ByVal fsModifiers&, ByVal vk&)
Private Declare Function UnregisterHotKey& Lib "user32" _
(ByVal hWnd&, ByVal id&)
Private Declare Function SetWindowLong& Lib "user32" Alias _
"SetWindowLongA" (ByVal hWnd&, ByVal nIndex&, ByVal dwNewLong&)
Private Declare Function CallWindowProc& Lib "user32" _
Alias "CallWindowProcA" (ByVal lpPrevWndFunc&, ByVal hWnd& _
, ByVal Msg&, ByVal wParam&, ByVal lParam&)
Private Const GWL_WNDPROC = (-4)
Private OldWndProc&

' Start the hook, and register the hotkey
Sub StartHook(ByVal hWnd&)
RegisterHotKey hWnd, 0, 0, &H72 ' F3
OldWndProc = SetWindowLong(hWnd, GWL_WNDPROC, AddressOf WndProc)
End Sub

' Stop the hook, and unregister the hotkey
Sub StopHook(ByVal hWnd&)
UnregisterHotKey hWnd, 0
SetWindowLong hWnd, GWL_WNDPROC, OldWndProc
End Sub

Function WndProc&(ByVal hWnd&, ByVal uMsg&, ByVal wParam&, ByVal lParam&)
Select Case uMsg
Case &H82 ' (WM_NCDESTROY)
Call StopHook(hWnd)
Case &H312 ' (WM_HOTKEY)
If wParam = 0 And UserForm1.Visible Then
UserForm1.ComboBox1.SetFocus
End If
End Select
WndProc = CallWindowProc(OldWndProc, hWnd, uMsg, wParam, lParam)
End Function

In the UserForm module:
Option Explicit
Private Declare Function FindWindow& Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName$, ByVal lpWindowName$)
Private hWnd&

Private Sub UserForm_Initialize()
hWnd = FindWindow(vbNullString, Me.Caption)
Call StartHook(hWnd)
End Sub

Private Sub UserForm_Terminate()
Call StopHook(hWnd)
End Sub

Regards,
MP
 

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