Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Advanced
Jul 28, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Restore Errant Focus to RichTextBox

If a RichTextBox control has the focus in a Multiple Document Interface (MDI) child form, it doesn't properly regain the focus after your application loses and regains focus. To fix this, you must subclass the MDI form and watch for the WM_ACTIVATE event. Set a Public variable equal to the window handle of the RichTextBox in its GotFocus event, and set that variable to zero in its LostFocus event. Use the SetFocus API function to force the focus to the RichTextBox:

'Module Code:
Private Declare Function CallWindowProc Lib _
	"user32" Alias "CallWindowProcA" (ByVal _
	lpPrevWndFunc As Long, ByVal hWnd As Long, _
	ByVal Msg As Long, ByVal wParam As Long, _
	ByVal lParam As Long) As Long
Private Declare Function SetFocusAPI Lib _
	"user32" Alias "SetFocus" (ByVal hWnd As _
	Long) As Long
Public Declare Function SetWindowLong Lib _
	"user32" Alias "SetWindowLongA" (ByVal hWnd _
	As Long, ByVal nIndex As Long, ByVal _
	dwNewLong As Long) As Long
Private Declare Sub CopyMem Lib "kernel32" Alias _
	"RtlMoveMemory" (Destination As Any, Source _
	As Any, ByVal Length As Long)

Public Const WM_ACTIVATE = &H6
Public Const WA_INACTIVE = 0
Public Const GWL_WNDPROC = (-4)
Public origWndProc As Long
Public lFocusHandle As Long

Public Function AppWndProc(ByVal hWnd As Long, _
	ByVal Msg As Long, ByVal wParam As Long, _
	ByVal lParam As Long) As Long
	Select Case Msg
			If WordLo(wParam) <> WA_INACTIVE Then
				If lFocusHandle Then SetFocusAPI _
			End If
	End Select
	AppWndProc = CallWindowProc(origWndProc, _
		hWnd, Msg, wParam, lParam)
End Sub

Private Function WordLo(LongIn As Long) As Integer
	Call CopyMem(WordLo, ByVal VarPtr(LongIn), 2)
End Function

'MDI Form code:
Private Sub MDIForm_Load()
	origWndProc = SetWindowLong(Me.hWnd, _
		GWL_WNDPROC, AddressOf AppWndProc)
End Sub

Private Sub MDIForm_Unload(Cancel As Integer)
	SetWindowLong Me.hWnd, GWL_WNDPROC, _
End Sub

'MDIChild Form code:
Private Sub RichTextBox1_GotFocus()
	lFocusHandle = RichTextBox1.hWnd
End Sub

Private Sub RichTextBox1_LostFocus()
	lFocusHandle = 0
End Function
Matt Hart
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date