devxlogo

Auto Select Content Component

Auto Select Content Component

We almost always need to develop forms in which the contents to the control have to be selected whenever the user tabs to a textbox or a combobox. For this we write two lines in the GotFocus event of each such control on the form. If the form contains 30 controls, we have to write 60 lines of code for them:

 Private Sub Text1_GotFocus()    Text1.SelStart = 0    Text1.SelLength = Len(Text1.Text)End Sub

But if we use the following component, we have to write just two lines ofcode:

 Option ExplicitDim mobjAutoSelectContent As New 
prjsel.clsSelectContent Private Sub Form_Load() mobjAutoSelectContent.Init MeEnd Sub

So the coding is reduced dramatically and so is the testing effort. The code behind the component is:

 Option ExplicitPrivate mobjfrm As Form  'stores the 
formPrivate mctrlActiveControl As Control
'stores the ActiveControlPrivate WithEvents mTimer As TimerPublic Sub Init(pfrm As Object) If TypeOf pfrm Is Form Then 'if the sent obj is FORM, set
it to the module obj mobjfrm Set mobjfrm = pfrm Else 'If the sent object is not the form,
iterate until the containingform is found Dim lctrl As Object 'set lctrl to the control passed to
the method Set lctrl = pfrm While Not (TypeOf lctrl Is Form) 'loop upwards using .container
prop of the control to reach tothe containing FORM Set lctrl = lctrl.Container Wend Set mobjfrm = lctrl End If 'Create a timer to select the text of the
active control Set mTimer = mobjfrm.Controls.Add("VB.Timer",
"Timer1_SelectContent" &CStr(mobjfrm.Controls.Count)) mTimer.Interval = 100 mTimer.Enabled = True End SubPrivate Sub Class_Terminate() Set mctrlActiveControl = Nothing Set mobjfrm = NothingEnd SubPrivate Sub mTimer_Timer() 'select the text of the active control If Not (mctrlActiveControl Is mobjfrm.ActiveControl)
Then 'Only if the currently Active control is
different than the one inthe mctrlActiveControl 'variable, do the following processing Set mctrlActiveControl = mobjfrm.ActiveControl If ((TypeOf mctrlActiveControl Is ComboBox)
Or (TypeOfmctrlActiveControl Is TextBox)) Then mctrlActiveControl.SelStart = 0 mctrlActiveControl.SelLength =
Len(mctrlActiveControl.Text) End If End IfEnd Sub
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
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