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 TrySetFocus Convenience Function

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.

For example, here's the help text for the Int32.TryParse method:

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

I'm going to start adopting TryXxx as my own personal naming convention for functions and methods that share this purpose.

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.

As with most convenience functions, TrySetFocus does not do anything particularly interesting.  However, the naming convention (TryXxx) and the encapsulation of the On Error Resume Next line combine to make any code that calls this function more readable.

We can use this function as a building block to do more interesting things.

' ----------------------------------------------------------------
' 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

Image by Pexels from Pixabay

All original code samples by Mike Wolfe are licensed under CC BY 4.0