The TrySetFocus Convenience Function

The TrySetFocus function attempts to set focus to a control. If the operation succeeds, it returns True; otherwise, it returns False.

The TryXxx Naming Convention

VB.Net has several standard library methods named TryXxx. These functions try to perform some operation, then return a boolean to indicate whether the operation succeeded or failed.

The Code: TrySetFocus

The following convenience function is simply a wrapper around the .SetFocus method of a control. The function attempts to set focus to the passed control object. If the operation succeeds, the function returns True. Otherwise, it returns False.

' ----------------------------------------------------------------
' Purpose : Attempts to set focus to the passed control.
' Returns True if successful; False otherwise.
' Author : Mike Wolfe
' Source : https://nolongerset.com/trysetfocus/
' ----------------------------------------------------------------
Function TrySetFocus(Ctl As Control) As Boolean
On Error Resume Next
Ctl.SetFocus
TrySetFocus = (Err.Number = 0)
End Function

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
No Longer Set

Advanced techniques and unique perspectives from Microsoft Access MVP Mike Wolfe.