Link to home
Start Free TrialLog in
Avatar of haneri
haneri

asked on

How do I change focus within event handler without raising additional events

I have a vb.net form that I want to be able to shift focus to a control (not the next one in tab order) based on the user input in the current control.  As an simplified example I’ve created a form with three textbox controls and the following event handlers.  


Private Sub TextBox_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter, TextBox2.Enter, TextBox3.Enter
    Debug.WriteLine(sender.name & " Enter Event")
End Sub

Private Sub TextBox_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave, TextBox3.Leave
    Debug.WriteLine(sender.name & " Leave Event")
End Sub

Private Sub TextBox_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus
     Debug.WriteLine(sender.name & " Lost Focus Event")
End Sub

Private Sub Assign_Focus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.Leave
     Debug.WriteLine(sender.name & " LEAVE EVENT")
     If TextBox2.Text = "a" Then
        Debug.WriteLine("  About to request change focus")
        TextBox1.Focus()
        Debug.WriteLine("  After focus change request")
     End If
End Sub

I ran the form tabbing at textbox1, entering “a” in textbox2 and then hit tab again.  The output from the Debug.Writeline statements is as follows:

TextBox1 Enter Event
TextBox1 Leave Event
TextBox2 Enter Event
TextBox1 Lost Focus Event
TextBox2 LEAVE EVENT
  About to request change focus
TextBox2 Lost Focus Event
TextBox2 LEAVE EVENT
  About to request change focus
  After focus change request
TextBox1 Enter Event
  After focus change request
TextBox1 Enter Event

Note that TextBox1.Focus causes a duplication of events

Is there a clean way of accomplishing a control focus shift without causing extra events or at least not having to remove the handlers of those events and later adding them back?
SOLUTION
Avatar of jrandallsexton
jrandallsexton

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of haneri
haneri

ASKER

I like your method of controlling adding and removing the event handlers (thanks) but I thought (and was hoping) there was some other way to "one time" cancel these events and jump to the execution of events of the new control where the focus was shifted.  Maybe there is another solution out there.
I'd be interested in seeing it too.

I'm sorry that I posted exactly what you specifically asked not to have - I just don't know any other way of doing it.

Maybe someone else will have something to add.

Good luck!
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial