Can't set focus in custom event handler

Okay, I am trying to set focus to a control on my form in the handler of a custom event. But it doesn't work. If txtBox1 has focus and my custom event is triggered, then I want to set focus to txtBox2. But the Me.txtBox2.focus statement below does not work. Here is a sample of my code:

Public Class clsReader

Public Event OnRead(ByVal e As System.ComponentModel.CancelEventArgs)

Private Sub ReceiveEvent() Handles SerialPort.OnComm
rxBuffer = SerialPort.InputArray
RaiseEvent OnRead(New System.ComponentModel.CancelEventArgs)
End Sub

...
End Class

Public Class myClass

Private WithEvents EIDReader As clsReader

Public Sub WeHaveARead(ByVal e As System.ComponentModel.CancelEventArgs) Handles EIDReader.OnRead
...Do some stuff
me.txtBox2.focus
End Sub

End Class

I am using VS2003 and CompactFramework 1.2. I am coding this app for and Windows CE 4.2 device. I am relativley new to .Net programming so I am sure I am missing something basic. This has been driving me nuts...any help is appreciated.

Answer this question

Can't set focus in custom event handler

  • ShyamD

    Got it. Alex your answer was correct, I was just having some problems implementing it. But it all works now as expected. Thanks for pointing me in the right direction.




  • Ayhan Yerli (TR-NL)

    Okay, that make sense. I made some changes and am now making a call to textBox.invoke, but I keep getting an ArgumentException on the call to invoke. A simplified example of my code looks like this:

    Public Class clsReader

    Public Event OnRead(ByVal e As System.ComponentModel.CancelEventArgs)

    Private Sub ReceiveEvent() Handles SerialPort.OnComm
    rxBuffer = SerialPort.InputArray
    RaiseEvent OnRead(New System.ComponentModel.CancelEventArgs)
    End Sub

    ...
    End Class

    Public Class myClass

    Private WithEvents EIDReader As clsReader

    Private Delegate Sub delAddItem()

    Public Sub WeHaveARead(ByVal e As System.ComponentModel.CancelEventArgs) Handles EIDReader.OnRead
    Dim del As delAddItem
    del = New delAddItem(AddressOf setFocus)
    ...Do some stuff
    Me.txtBox2.Invoke(del)
    End Sub

    Private Sub setFocus()
    ...
    Me.txtBox2.focus
    End Sub
    End Class

    I have a couple of questions: 1.) Does .NET CF implement the invoke functionality as I am trying to use it 2.) When I call raiseEvent OnRead does that continue to use the same thread as the Com Port or is it starting a new thread...and does that have anything to do with my error

    Thanks for any help.

    J-Llo


  • Simone1

    Yes, you are missing a call to Invoke. You need to use Textbox.Invoke to call textBox.Focus from a COM port handler since you are on a different thread

  • Can't set focus in custom event handler