Search code examples
.netvb.net

Why does my MessageBox show so many times?


I have an application which blocks certain websites using a list of websites from the hosts file, and once that website is blocked, an event is raised, which in my case, a MessageBox is shown.

The program works great, besides 1 annoying error which I can't seem to resolve, and that is, the MessageBox appears about 6 times, then, after those 6 times finishes up, the ERR_CONNECTION_RESET page appears.

Is there a way to limit the amounts of times a MessageBox is allowed to show, but also letting the traffic come through to get to the blocked website?

This is all of the code I'm using:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim blocker As BlockListener
        Dim thread As Thread
        blocker = New BlockListener
        thread = New Thread(New ThreadStart(AddressOf blocker.listen))
        thread.Start()
        AddHandler blocker.Blocked, AddressOf User_Blocked

    End Sub

    Private Sub User_Blocked()
        MessageBox.Show("Website successfully blocked!") <-- Shows 6 times!
    End Sub

    Public Class BlockListener
        Private port As Integer = 80
        Private listener As TcpListener
        Private BlockUsers As Boolean = True
        Public Event Blocked As EventHandler

        Public Sub listen()

            listener = New TcpListener(IPAddress.Parse("127.0.0.1"), port)

            listener.Start()
           
            While (BlockUsers)
                Dim clientConnection As TcpClient = listener.AcceptTcpClient
               
                clientConnection.Close()
                
                RaiseEvent Blocked(Me, EventArgs.Empty)
            End While
            '
            listener.Stop()
        End Sub

    End Class

Solution

  • It means that your code hits the while statement 6 times. While BlockUsers parameters is true, it will show the message and you try yo close the same connection 6 times.

          While (BlockUsers)
                Dim clientConnection As TcpClient = listener.AcceptTcpClient
    
                clientConnection.Close()
    
                'Set your parameter to False in order to do the transaction only one time.
                BlockUsers = False
    
                RaiseEvent Blocked(Me, EventArgs.Empty)
            End While
    
            BlockUsers = True