How do i code stuff for when the X button is clicked?

I want to stop threads when the X is clicked, how would I go about doing this?
Who is Participating?
Mike TomlinsonMiddle School Assistant TeacherCommented:
To stop the threads you would need to keep references to them.  You could create an ArrayList at your form level and add your threads to it as you create them.  Then you can use the closing event as cyberdevil has suggested to iterate thru them and call the Abort method for each one.  

Something like....

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private Threads As New ArrayList

    ' Somewhere in your code, create your threads and add them to the Threads ArrayList above...

    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        Dim t As System.Threading.Thread

        For Each t In Threads
            If t.IsAlive Then
            End If
    End Sub

End Class

Hi addicktz,
 Use the form_closing event. If you have your form open in the editor, over in the properties box you will notice a yellow lightning bolt if you go through this you will see events for closing and closed just double click the closing and it will create the event code for you, then just enter your code to stop or close anything you want in here.


The best thing to do would be to call the Dispose() method, this will do a garbage collection as you don't need to keep a record of anything then.

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.