Search code examples
vb.netforms

Form loses focus after clicking button


when clicking on the start button in the code below, the form seems to lose focus and I need to click the stop button twice to stop the count. (First click to activate the form, second to click the button) Can someone please explain this behavior or offer a better alternative?

Public Class Form1
    Dim testrunning As Boolean

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        testrunning = True
        test()
    End Sub

    Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
        testrunning = False
    End Sub

    Private Sub test()
        Dim count As Integer

        While testrunning = True
            count += 1
            TextBox1.Text = count.ToString
            System.Threading.Thread.Sleep(100)
            Application.DoEvents()
        End While
    End Sub
End Class

Solution

  • The form doesnt loose focus. The stop button does not gain focus after start-button is clicked- You could give it focus (btnStop.Focus()) in btnStart_Click. The other problem is that you should change your test-function. It is more like a benchmark. Read some articles about why using Application.DoEvents could be dangerous and is of poor design in general. It is better to use System.Windows.Forms.Timer or BackgroundWorkers instead. I think in your code the Application.DoEvents first only let the stop button gain focus and you need a second click to perform the click event.