devxlogo

Restore Errant Focus to RichTextBox

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 LongPrivate Declare Function SetFocusAPI Lib _	"user32" Alias "SetFocus" (ByVal hWnd As _	Long) As LongPublic Declare Function SetWindowLong Lib _	"user32" Alias "SetWindowLongA" (ByVal hWnd _	As Long, ByVal nIndex As Long, ByVal _	dwNewLong As Long) As LongPrivate Declare Sub CopyMem Lib "kernel32" Alias _	"RtlMoveMemory" (Destination As Any, Source _	As Any, ByVal Length As Long)Public Const WM_ACTIVATE = &H6Public Const WA_INACTIVE = 0Public Const GWL_WNDPROC = (-4)Public origWndProc As LongPublic lFocusHandle As LongPublic Function AppWndProc(ByVal hWnd As Long, _	ByVal Msg As Long, ByVal wParam As Long, _	ByVal lParam As Long) As Long	Select Case Msg		Case WM_ACTIVATE			If WordLo(wParam) <> WA_INACTIVE Then				If lFocusHandle Then SetFocusAPI _					lFocusHandle			End If	End Select	AppWndProc = CallWindowProc(origWndProc, _		hWnd, Msg, wParam, lParam)End SubPrivate 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 SubPrivate Sub MDIForm_Unload(Cancel As Integer)	SetWindowLong Me.hWnd, GWL_WNDPROC, _		origWndProcEnd Sub'MDIChild Form code:Private Sub RichTextBox1_GotFocus()	lFocusHandle = RichTextBox1.hWndEnd SubPrivate Sub RichTextBox1_LostFocus()	lFocusHandle = 0End Function
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist