Do...Loop alternative

Hi Experts,

The attached code waits for a message box to pop up then clicks it away. The problem is that the do...loop is causing this application to terminate incorrectly. How should I poll without using a do loop?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim WinHandle As IntPtr

        Me.Show()

        Do

            Threading.Thread.Sleep(1000)
            WinHandle = FindWindow(vbNullString, "Message box title")

            Application.DoEvents()

            If WinHandle.ToInt32 > 0 Then
                ClickButton()
            End If

        Loop

    End Sub

Open in new window

DColinAsked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Use a TIMER control....
0
 
CompanionCubeCommented:
Can you use this?
http://msdn.microsoft.com/en-us/library/eked04a7.aspx
Exit Do is often used after evaluating some condition
0
 
HainKurtSr. System AnalystCommented:
you have to exit loop

all loops are here: http://msdn.microsoft.com/en-us/library/ezk76t25.aspx
Do
            Threading.Thread.Sleep(1000)
            WinHandle = FindWindow(vbNullString, "Message box title")

            Application.DoEvents()

            If WinHandle.ToInt32 > 0 Then
                ClickButton()
                exit do
            End If
        Loop

Open in new window

0
 
DColinAuthor Commented:
Hi Idle_Mind

Would the attached code be an acceptable use of a timer to replace the do...loop from my question?

    Dim ManagePopUpFinished As Boolean = True

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.Show()
        Timer1.Enabled = True
        
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        If ManagePopUpFinished = True Then

            ManagePopUpFinished = False
            ManagePopUp()
            ManagePopUpFinished = True

        End If

    End Sub

    Private Sub ManagePopUp()

        Dim WinHandle As IntPtr

        WinHandle = FindWindow(vbNullString, "Message box title")
        TextBox1.Text = WinHandle.ToString & " @ " & Now.ToLongTimeString
        Application.DoEvents()

        If WinHandle.ToInt32 > 0 Then
            ClickButton()
        End If


    End Sub

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You don't need the DoEvents() call.

Also, if you have reached your "target" then disable the Timer so it doesn't keep firing...  =)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.