WebBrowser won't fire DocumentCompeted event or print - vb.net

So I've been looking around for a solution to this for a little over a week to no avail. I have a program that needs to be able to print htm(l) files and I'm having a terrible time getting it to comply.
This is the code I'm using at the moment:
Private Sub HtmlPrinterLaunch(i As Integer)
'Dim htmlWBPrinter As New WebBrowser()
'AddHandler htmlWBPrinter.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf HtmlPrinter)
'htmlWBPrinter.Visible = True
'htmlWBPrinter.ScriptErrorsSuppressed = False
'htmlWBPrinter.Show()
''frmHTMLPrint.wbPrintHtml.AllowNavigation = True
''AddHandler frmHTMLPrint.wbPrintHtml.DocumentCompleted, AddressOf HtmlPrinter
''frmHTMLPrint.wbPrintHtml.Visible = False
''frmHTMLPrint.wbPrintHtml.Navigate("file:///" & IO.Path.GetFullPath(_prints(i).SourcePathFileName))
''Application.Run(frmHTMLPrint)
''Dim appPath As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)
''Dim reportPath As String = Path.Combine(appPath, Path.GetFileName(_prints(i).SourcePathFileName))
''htmlWBPrinter.Url = New Uri(reportPath) 'New Uri(Path.Combine("file:///", reportPath)) 'New Uri("file://" & IO.Path.GetFullPath(_prints(i).SourcePathFileName))
'htmlWBPrinter.Url = (New Uri(Path.Combine("file:///" & IO.Path.GetFullPath(_prints(i).SourcePathFileName))))
'While ((htmlWBPrinter.DocumentText = ""))
' Thread.Sleep(10000)
'End While
'htmlWBPrinter.ShowPrintDialog()
'' htmlWBPrinter.Dispose()
Dim wb As New WebBrowser
AddHandler wb.DocumentCompleted, Sub() If wb.ReadyState = WebBrowserReadyState.Complete Then wb.Print()
wb.ScriptErrorsSuppressed = True
Dim url As New Uri(Path.Combine("file:///" & IO.Path.GetFullPath(_prints(i).SourcePathFileName)))
wb.Navigate(url)
End Sub
Private Sub HtmlPrinter(sender As Object, e As WebBrowserDocumentCompletedEventArgs)
state = 4
Dim wbPrinter As WebBrowser = CType(sender, WebBrowser)
wbPrinter.Print()
wbPrinter.Dispose()
'frmHTMLPrint.BeginInvoke(New Action(Sub() frmHTMLPrint.Close()))
End Sub
As you can see I have a couple attempts in there (kept some older code that sort of worked but I'd rather not us it as I kept getting pop ups)
Some likely related issues:
-the WebBrowser state stays in loading (1)
-the Url never updates with the file:///path even if I pass it directly
So to put it in brief, my in code WebBrowser control won't hit the DocumentCompleted event, nor will it print out files. I need this code to print documents with no input from the user. What am I missing here?
Edit:
So I've messed around with this some more. I have the webbrowser control on its own form and I can get it to load/print when called from the main thread, but I'm having no luck invoking it. My current code for invocation:
If wbPrintHtml.InvokeRequired Then
If url.SourcePathFileName = "about:blank" Then
wbPrintHtml.Invoke(CType(Sub()
wbPrintHtml.Navigate(url.SourcePathFileName)
End Sub, MethodInvoker))
Else
wbPrintHtml.Invoke(CType(Sub()
wbPrintHtml.Navigate("file:///" & url.SourcePathFileName)
End Sub, MethodInvoker))
End If
Else
If url.SourcePathFileName = "about:blank" Then
wbPrintHtml.Navigate(url.SourcePathFileName)
Else
wbPrintHtml.Navigate("file:///" & url.SourcePathFileName)
End If
End If

I finally got this to work as intended. It's not the prettiest thing in the world, but it functions, and I'm ok with that.
Public Class frmHTMLPrint
Public Shared formHandle As frmHTMLPrint
Private Sub wbPrintHtml_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles wbPrintHtml.DocumentCompleted
Dim wbPrinter As WebBrowser = CType(sender, WebBrowser)
If wbPrinter.ReadyState = WebBrowserReadyState.Complete AndAlso Not wbPrinter.Url.ToString() = "about:blank" Then
wbPrinter.Print()
End If
End Sub
Shared Function setURL(url As Reporter.ReportServer.PrintMessageType) As Boolean
If formHandle.wbPrintHtml.InvokeRequired Then
If url.SourcePathFileName = "about:blank" Then
formHandle.wbPrintHtml.Invoke(CType(Sub()
formHandle.wbPrintHtml.Navigate(url.SourcePathFileName)
End Sub, MethodInvoker))
Else
formHandle.wbPrintHtml.Invoke(CType(Sub()
formHandle.wbPrintHtml.Navigate("file:///" & url.SourcePathFileName)
End Sub, MethodInvoker))
End If
Dim wbReady As WebBrowserReadyState
formHandle.wbPrintHtml.Invoke(CType(Sub()
wbReady = formHandle.wbPrintHtml.ReadyState
End Sub, MethodInvoker))
While ((Not wbReady = WebBrowserReadyState.Complete))
Application.DoEvents()
formHandle.wbPrintHtml.Invoke(CType(Sub()
wbReady = formHandle.wbPrintHtml.ReadyState
End Sub, MethodInvoker))
End While
Return wbReady = 4
Else
If url.SourcePathFileName = "about:blank" Then
formHandle.wbPrintHtml.Navigate(url.SourcePathFileName)
Else
formHandle.wbPrintHtml.Navigate("file:///" & url.SourcePathFileName)
End If
While ((Not formHandle.wbPrintHtml.ReadyState = WebBrowserReadyState.Complete))
Application.DoEvents()
End While
Return formHandle.wbPrintHtml.ReadyState = 4
End If
End Function
Private Sub frmHTMLPrint_Load() Handles Me.Load
InitializeComponent()
Dim wbInitializer As New Reporter.ReportServer.PrintMessageType
formHandle = Me
wbInitializer.SourcePathFileName = "about:blank"
setURL(wbInitializer)
End Sub
End Class

Related

VB.NET Form.Show closes the application for unknown reason

VB.NET Framework 4.7.2
Visual Studio Community 2019 V16.11.2
I have a WinForms application and, for the most part, I start with a form to display the loading of datatables. This is handled in the Application Events module:
Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
If String.IsNullOrEmpty(My.Settings.TheCompany) Then
MainForm = FormConnection
Else
MainForm = FormDataLoad
End If
End Sub
When the datatables are all loaded the FormDataLoad has a close button which is enabled by the procedure which loads all the datatables:
With FormDataLoad
.ButtonClose.Visible = True
End With
When the button is pressed it calls another form which displays various charts etc based on the datatables which have been loaded:
Private Sub ButtonClose_Click(sender As Object, e As EventArgs) Handles ButtonClose.Click
Me.Close()
End Sub
Private Sub FormDataLoad_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
With FormOverview
.Show()
End With
End Sub
When FormOverview loads, its labels, charts etc are all initialised and drawn BUT, mysteriously, the form closes and the application ends. The Application Shutdown event is raised:
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
Private Sub MyApplication_Shutdown(sender As Object, e As EventArgs) Handles Me.Shutdown
MessageBox.Show("Closing the application for some unknown reason")
End Sub
When this message box is displayed it means that the application has closed but not as a result of any unhandled exception. Nowhere in the project is there any code to call FormOverview.close so I am at a loss to understand what is happening.
The form load code is here:
Private Sub FormOverview_Load(sender As Object, e As EventArgs) Handles Me.Load
With Me
'Set the form caption and back colour and font
.Text = "Retail Management Hero Data Visualisation Overview"
.BackColor = Color.GhostWhite
.Font = U.BasicFontSmall
'Add event handler for the DAL
AddHandler D.ConnectionOpened, AddressOf Connected
'Form level variables for the KPJs
Dim ITO As String = ""
Dim ATV As String = ""
Dim CRR As String = ""
Dim GMROI As String = ""
Dim OOS As String = ""
Dim StocksSales As String = ""
With KPIData.Rows(0)
Me.Text = My.Settings.TheCompany & " " & Me.Text
ITO = .Item("ITO").ToString
CRR = .Item("CRR").ToString
ATV = "€" & .Item("ATV").ToString
GMROI = "€" & .Item("GMROI").ToString
OOS = .Item("OOSRatio").ToString
StocksSales = .Item("StocksToSales").ToString
End With
For Each CTL As Control In .Controls
If TypeOf CTL Is Label Then
With CTL
If .Name.Contains("Value") Then
.Font = U.BasicFontSuperLarge
.BackColor = Color.Yellow
Else
.BackColor = U.Spurs
.ForeColor = Color.GhostWhite
End If
End With
End If
Next
With .LabelReportDate
.Text = "Reports As Of " & ReportDate
End With
With .LabelATVValue
.Text = U.DecimalToSuperSubFormat(ATV, True)
End With
With .LabelGMROIValue
.Text = U.DecimalToSuperSubFormat(GMROI, True)
End With
With .LabelCRRValue
.Text = U.DecimalToSuperSubFormat(CRR, True) & "%"
End With
With .LabelITOValue
.Text = U.DecimalToSuperSubFormat(ITO, True)
End With
With .LabelOOSValue
.Text = U.DecimalToSuperSubFormat(OOS, True) & "%"
End With
With .LabelStocksSalesValue
.Text = U.DecimalToSuperSubFormat(StocksSales, True) & "%"
End With
'Extract the names of the X and Y axes
Dim Xname As String = ""
Dim Yname As String = ""
With WineData
Xname = .Columns("Department").ColumnName
Yname = .Columns("Day").ColumnName
End With
'Draw the charts
DrawColumnChart(WineData, .ChartWine, "Wine sales", Xname, Yname, 250, False)
DrawColumnChart(OtherData, .ChartNonWine, "Other sales", Xname, Yname, 25, False)
'Centre on the screen
.CenterToScreen()
End With
End Sub
So, what should happen is that this form displays centre screen with charts etc all displayed correctly.
If anyone has any ideas I would be most grateful.
Dermot
I found out what was causing the problem.
In the Project's properties, in the Application tab, there Combo selector, Shutdown mode.
The option I had selected was When startup form closes - by changing this to When last form closes the issue went away.
Like many problems, when you look at it too long you can't see the woods for the trees.

Textbox not updating after thread abort

I have a thread which is executing a sub and within a sub I am updating the textbox during a "Do while" loop is in progress. I then created a cancel button to abort the thread.
When the button is clicked then the thread is aborted but the textbox (Status_Txtbox.Text) doesn't get updated with the message "Parsing is terminated". I tried to do the debug and I see the code is executed perfectly and if condition for thread.isalive satisfies but not sure why the textbox doesn't get updated with the message.
Any idea how to update the textbox once thread is aborted ?
Dim thrd1 As Thread
Private Sub Parse_Btn_2G_Click(sender As Object, e As RoutedEventArgs) Handles Parse_Btn_2G.Click
Parse_Btn_2G.IsEnabled = False
Scan_Btn_2G.IsEnabled = False
cancel_Btn_2G.IsEnabled = True
Dim start As DateTime = DateTime.Now
Dim elapsedtime As Double
Dim action As Action
thrd1 = New Thread(Sub()
ButtonClickWork.DoWork()
action = Sub()
Status_Txtbox.Text = "Parsing Data, Please wait..."
End Sub
Me.Dispatcher.Invoke(action)
End Sub)
thrd1.Start()
elapsedtime = (DateTime.Now.Subtract(start).TotalSeconds) / 60
elapsedtime = Math.Round(elapsedtime, 2)
Status_Txtbox.Text = " Managed Objects in XML, total time elapsed is" & elapsedtime
End Sub
Private Sub Cancel_Btn_2G_Click(sender As Object, e As RoutedEventArgs) Handles cancel_Btn_2G.Click
Try
If cancel_Btn_2G.IsEnabled = True Then
If MsgBox("Do you really want to exit Parsing?", vbYesNo) = MsgBoxResult.Yes Then
Parse_Btn_2G.IsEnabled = True
Scan_Btn_2G.IsEnabled = True
cancel_Btn_2G.IsEnabled = False
thrd1.Abort()
thrd1.Join()
If thrd1.IsAlive = False Then
Status_Txtbox.Text = "Parsing is terminated"
End If
End If
End If
Catch ex As ThreadAbortException
Status_Txtbox.Text = "Parsing is terminated"
End Try
End Sub

Windows Forms Modal Form Closes instantly when Base form is not Active

I have a Winforms Application which should notify the user when something in a database changes. For that i use Sql-Dependencys, which works fine.
When the Dependency fires i am able to show a form with some Buttons so the user can decide what he wants to do.
After one Button i want to show a Dialog, but the first Dialog always gets closed instantly.
The only fix i found until now is restoring the base form and activating it, but that is not the solution i am looking for.
For the code i am doing the Following:
This Method gets called when something changes in the Database
Private Sub NutzerBenachrichtigen(Aenderung As Aenderung)
If InvokeRequired Then
Me.BeginInvoke(New MethodInvoker(Sub()
ErzeugeBenachrichtigung(Aenderung)
End Sub))
Else
ErzeugeBenachrichtigung(Aenderung)
End If
End Sub
This Method Displays the first form (HeadsUp is taken from this here :https://github.com/glm9637/MaterialWinforms/blob/master/MaterialWinforms/Controls/HeadsUp.cs)
Private Sub ErzeugeBenachrichtigung(ByVal Aenderung As Aenderung)
If Aenderung.istAktuellerBenutzer Then
Dim objHeadsUp As New HeadsUp()
objHeadsUp.Titel = "Neue Aenderung"
If Aenderung.EventTyp.ToLower = "alter" Then
objHeadsUp.Text = String.Format("Du hast etwas an {0} {1} {2} geändert. {3}Willst du etwas dazu schreiben?", _
If(Aenderung.BetroffenesObjekt.EntitaetTyp.Name = New EntitaetTyp.Trigger().Name, "dem", "der"), _
Aenderung.BetroffenesObjekt.EntitaetTyp.Name, Aenderung.BetroffenesObjekt.Name, vbNewLine)
Else
objHeadsUp.Text = String.Format("Du hast {0} {1} {2} erstellt. {3}Willst du etwas dazu schreiben?", _
If(Aenderung.BetroffenesObjekt.EntitaetTyp.Name = New EntitaetTyp.Trigger().Name, "den", "die"), _
Aenderung.BetroffenesObjekt.EntitaetTyp.Name, Aenderung.BetroffenesObjekt.Name, vbNewLine)
End If
objHeadsUp.Tag = Aenderung.BetroffenesObjekt
Dim objButtonSchliessen = New MaterialFlatButton
objButtonSchliessen.Tag = objHeadsUp
objButtonSchliessen.Text = "Schliessen"
AddHandler objButtonSchliessen.Click, AddressOf SchliesseHeadsUp
objHeadsUp.Buttons.Add(objButtonSchliessen)
Dim objButtonHistorie = New MaterialFlatButton
objButtonHistorie.Tag = objHeadsUp
objButtonHistorie.Text = "Historieneintrag"
AddHandler objButtonHistorie.Click, AddressOf HistorienEintragHinzufuegen
objHeadsUp.Buttons.Add(objButtonSchliessen)
Dim objButtonDokumentation = New MaterialFlatButton
objButtonDokumentation.Tag = objHeadsUp
objButtonDokumentation.Text = "Dokumentation"
AddHandler objButtonDokumentation.Click, AddressOf DokumentationBearbeiten
objHeadsUp.Buttons.Add(objButtonSchliessen)
objHeadsUp.Buttons.Add(objButtonHistorie)
objHeadsUp.Buttons.Add(objButtonDokumentation)
objHeadsUp.Show()
ElseIf Aenderung.EventTyp = "CLOSE_MESSAGE" Then
Dim objHeadsUp As New HeadsUp()
objHeadsUp.Titel = "Achtung"
objHeadsUp.Text = "Die Anwendung muss für eine Aktualisierung geschlossen werden."
Dim objButtonSchliessen = New MaterialFlatButton
objButtonSchliessen.Tag = objHeadsUp
objButtonSchliessen.Text = "Anwendung Schliessen"
AddHandler objButtonSchliessen.Click, AddressOf AnwendungSchliessen
objHeadsUp.Buttons.Add(objButtonSchliessen)
objHeadsUp.Show()
Else
If mtc_UebersichtTabControl.SelectedTab.Text = "Aenderung" Then
mAenderungenUebersicht.Aktualisieren()
End If
End If
End Sub
Finally when the "Historieneintrag" Button is pressed this Method gets called:
Private Sub HistorienEintragHinzufuegen(sender As Object, e As EventArgs)
Dim blnNachDialogVerstecken As Boolean = False
Dim objFlatButton As MaterialFlatButton = sender
Dim HeadsUp As HeadsUp = objFlatButton.Tag
Dim Objekt As Entitaet = HeadsUp.Tag
Dim objOldLocation As System.Drawing.Point = Location
HeadsUp.Close()
Dim objDialogContent As New HistorienEintrag()
''Hacky: Ansonsten wird der Dialog sofort geschlossen
If WindowState = FormWindowState.Minimized Or Not Visible Then
Location = New System.Drawing.Point(-Width * 2, -Height - 2)
Me.Show()
blnNachDialogVerstecken = True
End If
Activate()
If MaterialDialog.Show("Neuer Historien Eintrag", objDialogContent, MaterialWinforms.Controls.MaterialDialog.Buttons.OKCancel, MaterialDialog.Icon.Info) = DialogResult.OK Then
Objekt.HistorieSpeichern(objDialogContent.Ergebniss)
End If
If blnNachDialogVerstecken Then
Me.Hide()
Location = objOldLocation
End If
End Sub
In here the first modal Form, so a MessageBox.Show("") or any other form closes Instantly if i don't do the show and activate part.
What am i doing wrong here?
Project > (Project) Properties > Application > Shutdown mode
change from when startup form closes to when last form closes

Moving a form does not work

I would like to move my borderless form once a timer get's called, however, it is not doing anything. It also doesn't give an error. It just does nothing... Hope someone can help.
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Debug.WriteLine("Timer has ticked. " & TimeOfDay)
Try
If Screen.AllScreens.Length = 2 Then
Debug.WriteLine("Screen is connected!")
Me.Location = New Point(Screen.AllScreens(1).Bounds.X, Screen.AllScreens(1).Bounds.Y)
Else
Debug.WriteLine("Screen is not connected!")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Use this :
If Screen.AllScreens.Length > 1 Then
' To make it work with more than 2 screens (never tried though)
Dim SecondaryScreenIndex As Int32 = -1
' Find Secondary Screen...
' Because it happens AllScreens(0) is not always PrimaryScreen..?
For i As Int32 = 0 To Screen.AllScreens.Length - 1
If Screen.AllScreens(i) IsNot Screen.PrimaryScreen Then
SecondaryScreenIndex = i
Exit For
End If
Next
If SecondaryScreenIndex > -1 Then
Debug.WriteLine("Screen is connected!")
Me.Location = New Point( _
Screen.AllScreens(SecondaryScreenIndex ).Bounds.Left, _
Screen.AllScreens(SecondaryScreenIndex ).Bounds.Top)
' Try Left and Top if it makes any difference.
Else
Debug.WriteLine("Screen is not connected!")
End If
End If
The following is optional
.
(or garbage)
I would advise you to create a Class, like Screen_Class or ScreenTools with below content that handles the monitoring/checks on the available Screens if you plan to load more Forms...
' ...
Public Shared Event ScreensChanged() ' <- capture this event..
Private Shared ps_ScreensMonitor As System.Windows.Forms.Timer = Nothing
Private Shared ps_MonitorCount As Int32 = 0
Private Shared ps_PrimaryScreenIndex As Int32 = 0
Public Shared Sub BeginScreensMonitoring()
If ps_ScreensMonitor Is Nothing Then
ps_ScreensMonitor = New System.Windows.Forms.Timer()
ps_ScreensMonitor.Interval = 500
AddHandler ps_ScreensMonitor.Tick, AddressOf HandleScreensMonitoring
End If
If Not ps_ScreensMonitor.Enabled Then
ps_ScreensMonitor.Enabled = True
End If
End Sub
Public Shared Sub SuspendScreensMonitoring()
If ps_ScreensMonitor IsNot Nothing Then
ps_ScreensMonitor.Enabled = False
RemoveHandler ps_ScreensMonitor.Tick, AddressOf HandleScreensMonitoring
ps_ScreensMonitor.Dispose()
ps_ScreensMonitor = Nothing
End If
End Sub
Private Shared Sub HandleScreensMonitoring(sender As Object, e As System.EventArgs)
Dim i As Int32
Dim AnythingChanged As Boolean = False
' Locate PrimaryScreen...
For i = 0 To Screen.AllScreens.Length - 1
If Screen.AllScreens(i) Is Screen.PrimaryScreen Then
If ps_PrimaryScreenIndex <> i Then
ps_PrimaryScreenIndex = i
AnythingChanged = True
End If
Exit For
End If
Next
' Find if a screen has been connected or disconnected
If ps_MonitorCount <> Screen.AllScreens.Length Then
ps_MonitorCount = Screen.AllScreens.Length
AnythingChanged = True
End If
' Fire the event to notify the changes.
If AnythingChanged Then
RaiseEvent ScreensChanged
End If
End Sub
' WARNING !!! THIS IS NOT THREAD SAFE !
Then launch monitoring from your main Form constructor or Loading :
' ...
Screen_Class.BeginScreensMonitoring()
AddHandler Screen_Class.ScreensChanged, AddressOf HandleScreensUpdate
' ...
Private Sub HandleScreensUpdate()
' Do here whatever you want here...
' Get the index of the PrimaryScreen for example,
' (^^ you can also make a static ReadOnly PrimaryScreenIndex Property
' in the custom class above and even add a
' Static ReadOnly SecondaryScreenIndex if you want)
End Sub
Then you could control the loading of any form depending on the members you make available on this custom Class. Making this approach useable for your requirements depends on how you're using your forms...

VB.net ListView Adding Items Multiple Times

I am having an issue where I get multiple entries in my ListView for the same item if I run my action more than once.
I am creating a simple network scanner/hostname grabber that will add the items to the listview as they come back alive to my ping test.
When I run it the first time it runs fine and creates one entry as it should.
When I run it subsequent times it creates the item as many times as I have ran the code ex. 3rd time hitting start it creates each entry 3 times when it should just create the entry once.
Here is my go button code:
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
Dim verifyIP
ListView1.Items.Clear()
chkDone = 0
verifyIP = ipChk(ipAdd.Text)
If verifyIP = 1 Then
ipAddy = Split(ipAdd.Text, ".")
pingTest1.WorkerReportsProgress = True
pingTest1.WorkerSupportsCancellation = False
AddHandler pingTest1.ProgressChanged, AddressOf pingTest1_ProgressChanged
pingTest1.RunWorkerAsync()
pingTest2.WorkerReportsProgress = True
pingTest2.WorkerSupportsCancellation = False
AddHandler pingTest2.ProgressChanged, AddressOf pingTest2_ProgressChanged
pingTest2.RunWorkerAsync()
pingTest3.WorkerReportsProgress = True
pingTest3.WorkerSupportsCancellation = False
AddHandler pingTest3.ProgressChanged, AddressOf pingTest3_ProgressChanged
pingTest3.RunWorkerAsync()
pingTest4.WorkerReportsProgress = True
pingTest4.WorkerSupportsCancellation = False
AddHandler pingTest4.ProgressChanged, AddressOf pingTest4_ProgressChanged
pingTest4.RunWorkerAsync()
While chkDone < 4
wait(25)
End While
Else
MsgBox("IP Invalid")
End If
MsgBox("Done")
End Sub
Here is the code from one of the background workers I am using:
Private WithEvents pingTest1 As BackgroundWorker = New BackgroundWorker
Private Sub pingTest1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles pingTest1.DoWork
Try
Dim hostCheck
pingResult1 = 0
pingTestDone1 = 0
tryIP1 = ipAddy(0) & "." & ipAddy(1) & "." & ipAddy(2) & ".1"
If My.Computer.Network.Ping(tryIP1) = True Then
'Dim pingsender As New Net.NetworkInformation.Ping
'If pingsender.Send(tryIP).Status = Net.NetworkInformation.IPStatus.Success Then
Try
'Dim host As System.Net.IPHostEntry
hostCheck = ""
'host = System.Net.Dns.GetHostByAddress(tryIP3)
'MsgBox(host.HostName)
'host3 = host.HostName
'hostCheck = System.Net.Dns.GetHostEntry(tryIP3).HostName
hostCheck = System.Net.Dns.GetHostByAddress(tryIP1)
'get the hostname property
hostCheck = hostCheck.HostName
pingTest1.ReportProgress("1", hostCheck)
Catch f As Exception
'MsgBox("Error: " & f.Message)
pingTest1.ReportProgress("1", "No Hostname Found")
End Try
Else
pingResult1 = 2
End If
Catch d As Exception
MsgBox("There was an error trying to ping the IP Address: " & d.Message)
End Try
End Sub
Private Sub pingTest1_ProgressChanged(e.ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
MsgBox("Hey")
Dim str(2) As String
Dim itm As ListViewItem
str(0) = tryIP1 & " Is Alive!!!"
str(1) = e.UserState
itm = New ListViewItem(str)
ListView1.Items.Add(itm)
str(0) = ""
str(1) = ""
itm = Nothing
End Sub
Private Sub pingTest1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles pingTest1.RunWorkerCompleted
chkDone = chkDone + 1
End Sub
I added the Hey box and sure enough the ProgressChanged event gets triggered the amount of times I have hit the Go button. Is it something I have coded incorrectly?
It's most likely because you're adding, but not removing your handlers for the progress changed, so you're handling the event multiple times.
Try adding your Progress Changed Event Handlers when you're instantiating your Background workers, rather than every time you click your button. This way they will only handled once.