Don’t use SetFocus on invisible controls

Don’t use SetFocus on invisible controls

In the Show event of a form you might be tempted to use SetFocus to select which field the end user should begin working with. However, this method raises an error 5 when applied on a control that is currently invisible.

If the logic of your application should give the focus always to the same control, it is much better to achieve this using the TabIndex property at design time. Conversely, if the form should behave differently according to other conditions, you should use a different approach. I usually prefer to set the focus in the Form_Activate event

Sub Form_Activate()  Static done As Boolean  If Not done Then    done = True    Text1.SetFocus  End IfEnd Sub

Note that we need a Static variable to discern the first activation of the form


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