Form reloading data and Class variables resetting in VB.net - vb.net

This program basically goes to a websites and gets all the links in a specific div tag.
It then navigates to each link and gets the links in those pages as well.
However, after getting the first links successfully and traveling to the first website, it recheck the windows form data and resets the class variables to their original values, thus losing all the links.
Why does it reload the windows form data and how could I keep the previous data?
Imports System.Text.RegularExpressions
Public Class Form
Private stage As String = "Getting Page Links"
Dim PageUrls() As String = {}
Dim PageHtml() As String = {}
Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load
WebBrowser.Navigate("websiteurlhidden")
End Sub
Private Sub WebBrowser_DocumentCompleted(sender As Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser.DocumentCompleted
If WebBrowser.ReadyState = WebBrowserReadyState.Complete Then
Try
Select Case stage
Case "Getting Page Links"
Dim htmlDocument As HtmlDocument = Me.WebBrowser.Document
Dim htmlElementCollection As HtmlElementCollection = htmlDocument.GetElementsByTagName("DIV")
For Each htmlElement As HtmlElement In HtmlElementCollection
Dim imgUrl As String = htmlElement.GetAttribute("classname")
If imgUrl = " nine " Then
Dim linkIndex As Integer = 0
Dim index2 As Integer = 0
For Each link As HtmlElement In htmlElement.GetElementsByTagName("a")
If linkIndex >= 26 Then
If Not String.IsNullOrEmpty(link.GetAttribute("href")) Then
ReDim Preserve PageUrls(index2)
PageUrls(index2) = link.GetAttribute("href")
' MessageBox.Show(link.GetAttribute("href"))
' MessageBox.Show(PageUrls(linkIndex))
index2 = index2 + 1
End If
End If
linkIndex = linkIndex + 1
Next
For Each str As String In PageUrls
' MessageBox.Show(str)
Next
stage = "Going through pages"
End If
Next
GoThroughPages()
Case "Going through pages"
Dim htmlDocument As HtmlDocument = Me.WebBrowser.Document
Dim htmlElementCollection As HtmlElementCollection = htmlDocument.GetElementsByTagName("DIV")
Dim linkIndex As Integer = 0
For Each htmlElement As HtmlElement In HtmlElementCollection
Dim imgUrl As String = htmlElement.GetAttribute("classname")
If imgUrl = " nine " Then
ReDim Preserve PageHtml(linkIndex)
'need to make permanent.
PageHtml(linkindex) = htmlElement.ToString()
Dim PageDownloadLinks = htmlElement.GetElementsByTagName("a")
End If
End
Next
' GoThroughPages()
Case Else
MessageBox.Show("case else")
End Select
Catch ex As Exception
' MessageBox.Show(ex.Message & " " & ex.ToString)
End Try
End If
End Sub
Private Sub GoThroughPages()
For linkIndex As Integer = 0 To PageUrls.Count - 1
MessageBox.Show(PageUrls(linkIndex))
WebBrowser.Navigate(PageUrls(linkIndex))
Delay(3)
While (WebBrowser.IsBusy)
Application.DoEvents()
End While
Next
End Sub
Sub Delay(ByVal dblSecs As Double)
Const OneSec As Double = 1.0# / (1440.0# * 60.0#)
Dim dblWaitTil As Date
Now.AddSeconds(OneSec)
dblWaitTil = Now.AddSeconds(OneSec).AddSeconds(dblSecs)
Do Until Now > dblWaitTil
Application.DoEvents() ' Allow windows messages to be processed
Loop
End Sub
End Class

The simple solution is to change:
Dim linkIndex As Integer = 0
to
Static linkIndex As Integer = 0
This will cause linkIndex to retain its value between calls and the ReDim Preserve PageHtml(linkIndex) will not be reset on each call.

Related

How to build a for each with a customized Module

Hi i have build a customized module do get elements by classname but i can not get work with for each function.
Well i try to get the loop on the code that call my elements by classname wich is a customized module
Normally its easy to get the loop but with this Customized Module , i can not find the way to this to work.
I am new yet on vb , and i can not find any example to do it wright
This is my code i need to perform a loop
I need some some thing like this
For Each cuele In ele
Next
But its give me an error
Expression is of type 'System.Windows.Forms.HtmlElement', which is not a collection type
I have try in a different way but i get a null exception
Imports System.Text
Imports System.Net
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form3
Dim WithEvents htmldoc As HtmlDocument
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'TextBox1.Text = ""
WebBrowser1.Navigate(TextBox1.Text)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
htmldoc = WebBrowser1.Document
'WebBrowser1.Document.Forms(0).InvokeMember("click")
'WebBrowser1.Document.Forms(0).InvokeMember("submit")
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
'ListBox1.Items.Add(webpageelement.GetAttribute("title").ToString)
'ListBox1.Items.Add(webpageelement.GetAttribute("href").ToString)
Dim PageElement As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("time")
For Each CurElement As HtmlElement In PageElement
'TextBox1.Text = TextBox1.Text + CurElement.GetAttribute("Liga NOS") + Environment.NewLine
'ListBox2.Items.Add(CurElement.GetAttribute("datetime") + Environment.NewLine)
Next
Dim PageElement2 As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("td")
For Each CurElement As HtmlElement In PageElement2
'TextBox1.Text = TextBox1.Text + CurElement.GetAttribute("Liga NOS") + Environment.NewLine
'ListBox1.Items.Add(CurElement.GetAttribute("data-content") + Environment.NewLine)
Next
Dim PageElement3 As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("img")
For Each CurElement As HtmlElement In PageElement3
'TextBox1.Text = TextBox1.Text + CurElement.GetAttribute("Liga NOS") + Environment.NewLine
'ListBox3.Items.Add(CurElement.GetAttribute("alt") + Environment.NewLine)
Next
Next
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
If ListBox1.GetItemText(ListBox1.Items(i)) = String.Empty Then
ListBox1.Items.RemoveAt(i)
End If
Next i
For i As Integer = ListBox2.Items.Count - 1 To 0 Step -1
If ListBox2.GetItemText(ListBox2.Items(i)) = String.Empty Then
ListBox2.Items.RemoveAt(i)
End If
Next i
Dim ele As HtmlElement = WebBrowser1.Document.GetElementsByClassName("league-data")(0)
'TextBox1.Text = ele.InnerText
ListBox2.Items.Add(ele.InnerText)
Dim ArrayTag As New ArrayList
For Each item As HtmlElement In
Form1.WebBrowser1.Document.GetElementsByTagName("div")
ArrayTag.Add(item.InnerText)
Next
ListBox2.Items.Add(ArrayTag(64))
End Sub
End Class
OK This might well work, but I can't test it. I've altered the extension a little, so that it creates a list rather than a HtmlElementCollection (It seems that these are read-only)
<System.Runtime.CompilerServices.Extension()>
Public Function GetElementsByClassName(Source As HtmlElementCollection, ClassName As String) As List(Of HtmlElement)
Dim output As New List(Of HtmlElement)
For i As Integer = 0 To Source.Count - 1
Try
If Source(i).GetAttribute("className") = ClassName Then
output.Add(Source(i))
End If
Catch ex As Exception
End Try
Next
Return output
End Function
And edited the form code so that it also deals with a list instead of the HtmlElementCollection
For Each cuele As HtmlElement In ele
ListBox2.Items.Add(cuele.InnerText)
Next
Hopefully this should work.
I also suggest that you use a list instead of an ArrayList as Lists are faster and strongly typed ..
Dim ArrayTag As New List(Of String)
For Each item As HtmlElement In Form1.WebBrowser1.Document.GetElementsByTagName("div")
ArrayTag.Add(item.InnerText)
Next
ListBox2.Items.Add(ArrayTag(64))

multi-threaded code to check proxies

I'm suffering with this VB.Net 2017 code which is supposed to check if Proxies working or not. Sometimes it reach to an end successfully, and sometimes the program never reach and end or take lots of time to do so, although I have specified the timeout for every webrequest to be 11000... Also, the list of working proxies always has duplicates! I don't know how that happens, althoug the original (raw) list is unique!
Could you please help? This is supposed to wait till the 99 threads finished then another 99 (or the remaining threads) kick-started.
P.S. MYWEBSITE.com works for me only and it displays the IP address of the visitor, i.e. to double check if the proxy has worked fine
Imports System.Net
Imports System.IO
Imports System
Imports System.Text.RegularExpressions
Imports System.Threading
Public Class frmMain
Dim FinalWorkingProxies As New List(Of String)()
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Control.CheckForIllegalCrossThreadCalls = False
PB.Maximum = txtRawIP.Lines.Count
PB.Value = 0
StartCheckingIP(0)
End Sub
Function StartCheckingIP(ByVal num As Integer)
For I As Integer = num To txtRawIP.Lines.Count - 1
Dim StrIPOnly As String = txtRawIP.Lines(I)
StrIPOnly = Trim(StrIPOnly.TrimStart("0"c)) 'remove any leading zeros
Try
Dim clsThreads As New System.Threading.Thread(AddressOf CheckIP)
clsThreads.Start(StrIPOnly)
Catch ex As Exception
MsgBox(I)
End Try
If (I > 0 And (I Mod 99 = 0)) Then Exit For
Next
Return True
End Function
Private Function CheckIP(ByVal Prox As String) As Boolean
'txtHTML.Text += vbCrLf & Prox
'txtHTML.Refresh()
Dim txtWebResult As String = ""
Dim OriginalFullProx As String = Trim(Prox)
Dim proxyObject As WebProxy = New WebProxy("http://" & OriginalFullProx & "/")
proxyObject.BypassProxyOnLocal = True
Prox = Prox.Substring(0, Prox.IndexOf(":"))
Dim sURL As String
sURL = "http://MYWEBSITE.com/testip.php"
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
wrGETURL.Proxy = proxyObject
wrGETURL.Timeout = 6000
txtWebResult = "Dosn't work"
Try
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
txtWebResult = sLine
End If
txtWebResult = Regex.Replace(txtWebResult, “^\s+$[\r\n]*”, “”, RegexOptions.Multiline)
If (Trim(Prox) = Trim(txtWebResult)) Then
FinalWorkingProxies.Add(OriginalFullProx)
End If
Catch ex As Exception
txtWebResult = "Dosn't work"
End Try
If (PB.Value < PB.Maximum) Then PB.Value += 1
PB.Refresh()
If (PB.Value = PB.Maximum) Then
txtFilteredIP.Clear()
Randomize()
Dim RRR As Integer = CInt(Math.Ceiling(Rnd() * 1000)) + 1
Thread.Sleep(RRR)
If (txtFilteredIP.Text <> "") Then Return False
Dim str As String
For Each str In FinalWorkingProxies
txtFilteredIP.Text += str & vbCrLf
Next
ElseIf ((PB.Value - 1) > 0 And ((PB.Value - 1) Mod 99 = 0)) Then
StartCheckingIP(PB.Value)
End If
Return True
End Function
Private Sub txtRawIP_TextChanged(sender As Object, e As EventArgs) Handles txtRawIP.TextChanged
lblRawIPTotal.Text = "Total: " & txtRawIP.Lines.Count
End Sub
Private Sub txtFilteredIP_TextChanged(sender As Object, e As EventArgs) Handles txtFilteredIP.TextChanged
lblFilteredIPTotal.Text = "Total: " & txtFilteredIP.Lines.Count
End Sub
End Class
Here is the modified code, but it stills takes long of time to finalize long list of proxies, although I sat max concurrent connection to 2000 and timeout to 8sec. Please help. Thanks.
Public Class frmMain
Dim FinalWorkingProxies As New List(Of String)()
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
'Control.CheckForIllegalCrossThreadCalls = False
ServicePointManager.Expect100Continue = False
ServicePointManager.DefaultConnectionLimit = 2000
'ServicePointManager.Expect100Continue = True
FinalWorkingProxies.Clear()
PB.Maximum = txtRawIP.Lines.Count
PB.Value = 0
StartCheckingIP(0)
End Sub
Function StartCheckingIP(ByVal num As Integer)
For I As Integer = num To txtRawIP.Lines.Count - 1
Dim StrIPOnly As String = txtRawIP.Lines(I)
StrIPOnly = Trim(StrIPOnly.TrimStart("0"c)) 'remove any leading zeros
Try
Dim clsThreads As New System.Threading.Thread(AddressOf CheckIP)
clsThreads.Start(StrIPOnly)
Catch ex As Exception
MsgBox(I)
End Try
If (I > 0 And (I Mod 333 = 0)) Then Exit For
Next
Return True
End Function
Private Function CheckIP(ByVal Prox As String) As Boolean
'txtHTML.Text += vbCrLf & Prox
'txtHTML.Refresh()
Dim txtWebResult As String = ""
Dim OriginalFullProx As String = Trim(Prox)
Dim proxyObject As WebProxy = New WebProxy("http://" & OriginalFullProx & "/")
proxyObject.BypassProxyOnLocal = True
Prox = Prox.Substring(0, Prox.IndexOf(":"))
Dim sURL As String
sURL = "http://MYWEBSITE.com/testip.php"
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
wrGETURL.Proxy = proxyObject
wrGETURL.Timeout = 8000
txtWebResult = "Dosn't work"
Try
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
txtWebResult = sLine
End If
txtWebResult = Regex.Replace(txtWebResult, “^\s+$[\r\n]*”, “”, RegexOptions.Multiline)
If (Trim(Prox) = Trim(txtWebResult)) Then
'Now know exact country
sURL = "http://ip-api.com/xml/" & Prox
wrGETURL = WebRequest.Create(sURL)
wrGETURL.Proxy = proxyObject
wrGETURL.Timeout = 8000
objStream = wrGETURL.GetResponse.GetResponseStream
Dim objReader2 As New StreamReader(objStream)
Dim FullCODEOFAPI As String = objReader2.ReadToEnd()
Dim XMLR As XmlReader
XMLR = XmlReader.Create(New StringReader(FullCODEOFAPI))
XMLR.ReadToFollowing("country")
XMLR.Read()
OriginalFullProx += "-" + XMLR.Value
FinalWorkingProxies.Add(OriginalFullProx)
End If
Catch ex As Exception
txtWebResult = "Dosn't work"
End Try
If (PB.Value < PB.Maximum) Then UpdatePB(1)
If (PB.Value = PB.Maximum) Then
UpdateFilteredList(1)
ElseIf ((PB.Value - 1) > 0 And ((PB.Value - 1) Mod 333 = 0)) Then
StartCheckingIP(PB.Value)
End If
Return True
End Function
Private Delegate Sub UpdatePBDelegate(ByVal PBVal As Integer)
Private Sub UpdatePB(ByVal PBVal As Integer)
If PB.InvokeRequired Then
PB.Invoke(New UpdatePBDelegate(AddressOf UpdatePB), New Object() {PBVal})
Else
PB.Value += PBVal
PB.Refresh()
End If
End Sub
Private Delegate Sub UpdateFilteredListDelegate()
Private Sub UpdateFilteredList(ByVal TMP As Integer)
If txtFilteredIP.InvokeRequired Then
txtFilteredIP.Invoke(New UpdatePBDelegate(AddressOf UpdateFilteredList), New Object() {TMP})
Else
txtFilteredIP.Clear()
Dim str As String
For Each str In FinalWorkingProxies
txtFilteredIP.Text += str & vbCrLf
Next
End If
End Sub
Private Sub txtRawIP_TextChanged(sender As Object, e As EventArgs) Handles txtRawIP.TextChanged
lblRawIPTotal.Text = "Total: " & txtRawIP.Lines.Count
End Sub
Private Sub txtFilteredIP_TextChanged(sender As Object, e As EventArgs) Handles txtFilteredIP.TextChanged
lblFilteredIPTotal.Text = "Total: " & txtFilteredIP.Lines.Count
End Sub
Private Sub btnLoadList_Click(sender As Object, e As EventArgs) Handles btnLoadList.Click
OFD.ShowDialog()
If (OFD.FileName <> "") Then
txtRawIP.Text = File.ReadAllText(OFD.FileName)
End If
End Sub
End Class

Alternate between hiding and showing different controls on form

I'm working on a small project to dynamically add browsers to a form and alternate them on a timer so every tick one browser changes from visible=true to false and so on, but can't for the life of me figure out how to do it.
'Some Variables
Dim Browsers() As WebControl
Dim XMLFile As String = "\\********.xml"
Dim Controllist As New ArrayList
Dim BrowserCount As Integer
Private Sub Left_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Set form properties
Me.Location = New Point(Screen.AllScreens(0).Bounds.X, Screen.AllScreens(0).Bounds.Y)
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
Me.WindowState = FormWindowState.Maximized
Me.TopMost = True
Try
'Load xml file with urls
Dim xmlDoc As New XmlDocument
Dim nodeList As XmlNodeList = xmlDoc.SelectNodes("//BottomLeft/url")
xmlDoc.Load(XMLFile)
'Define number of browsers based on xml
Dim numberOfBrowsers As Integer = nodeList.Count + 1
ReDim Browsers(numberOfBrowsers)
'Put urls in an array to use later
Dim UrlList As New ArrayList
Debug.WriteLine("Number of browser is: " & numberOfBrowsers)
For Each inst As XmlNode In nodeList
UrlList.Add(inst.InnerText)
Debug.WriteLine("Added to array: " & inst.InnerText)
Next
'Set properties and add the browsers
For counter As Integer = 0 To numberOfBrowsers - 1
Debug.WriteLine("Start adding browsers")
Browsers(counter) = New WebControl
With Browsers(counter)
Debug.WriteLine("Setting properties")
.Dock = DockStyle.Fill
.Name = "Browers" & counter
.Source = New Uri(UrlList(counter))
If counter = 0 Then
.Visible = True
Else
.Visible = False
End If
End With
'Add the actual browsers after the properties have been set
Me.Controls.Add(Browsers(counter))
AddHandler Browsers(counter).LoadingFrameComplete, AddressOf All_Browsers_Loaded
Debug.WriteLine("Browsers is added. Current Count is: " & counter)
Next
Catch ex As Exception
Debug.WriteLine(ex)
End Try
'Count all the added browsers to alternate between them
Dim allWebBrowser As New List(Of Control)
For Each web As WebControl In FindControlRecursive(allWebBrowser, Me, GetType(WebControl))
Debug.WriteLine("Webcontrols on form: " & web.Name)
BrowserCount = +1
Next
'Start timer to switch browsers
Timer1.Interval = 1000
Timer1.Start()
End Sub
Private Sub All_Browsers_Loaded(ByVal sender As System.Object, ByVal e As Awesomium.Core.FrameEventArgs)
Dim Browser As WebControl = DirectCast(sender, WebControl)
Browser.Zoom = "80"
Debug.WriteLine("Browsers is now zoomed out?")
End Sub
Public Function ChangeBrowser()
Dim Changed As Boolean
For I As Integer = 0 To BrowserCount
With Browsers(I)
If Browsers(I).Visible = True Then
Browsers(I).Visible = False
Changed = True
End If
If Changed = True Then
Browsers(I).Visible = True
Changed = False
End If
If I = BrowserCount Then
Browsers(0).Visible = True
Continue For
End If
End With
Next
Return False
End Function
In the ChangeBrowser() function I'm trying to get the first visible browser and make it not visible. Then set the Changed Boolean to true.
Whats the best way to handle this?

Making a string from a listbox

I have 2 projects, one which has a highscorelist stored on it, and one which tries to add highscores to that list and retrieve all items on the list. Trying to put items on the list works good, but retrieving the list doesn't work well. Here's the code:
Option Strict On
Option Explicit On
Imports System.Net.Sockets
Imports System.Threading
Public Class Main
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Dim connected As Boolean
Private Sub cmd_start_Click(sender As Object, e As EventArgs) Handles cmd_start.Click
server.Start()
cmd_start.Enabled = False
cmd_stop.Enabled = True
lbl_status.Text = "Running"
lbl_status.ForeColor = Color.Green
tmr.Start()
End Sub
Private Sub cmd_stop_Click(sender As Object, e As EventArgs) Handles cmd_stop.Click
server.Stop()
cmd_start.Enabled = True
cmd_stop.Enabled = False
lbl_status.Text = "Not running"
lbl_status.ForeColor = Color.Red
tmr.Stop()
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connected = False
CheckForIllegalCrossThreadCalls = False
End Sub
Dim x As Integer = 0
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
If server.Pending Then
client = server.AcceptTcpClient()
stream = client.GetStream()
tmr.Stop()
read()
Else
tmr.Start()
End If
lbl_mseconds.Text = "Relative time: " & x
x += 1
End Sub
Private Sub SendMessage(message As String)
Dim sendtext() As Byte = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(sendtext, 0, sendtext.Length)
stream.Flush()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i = 1 To listbox_highscores.Items.Count - 1
tosend &= "," & listbox_highscores.Items(i).ToString
Next
MsgBox(tosend)
SendMessage(tosend)
End If
tmr.Start()
End Sub
End Class
On the other project I have this:
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Friend Sub sendHighscore(name As String, score As Integer)
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#1#" & score & "-" & name)
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
End Sub
Friend Sub getHighscoreList()
ListBox_highscores.Items.Clear()
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
ListBox_highscores.Items.Add("Couldn't connect")
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#2#")
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
read()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = Encoding.ASCII.GetString(rec)
Label2.Text = rectext
For Each item In rectext.Split(",")
ListBox_highscores.Items.Add(item)
Next
End Sub
Then when I use the sub sendHighscore() with a name and score, everything perfectly works and it shows in the other project on the list, but when I use the sub getHighscoreList() the list on the second project only contains the first item from the first list. Does someone has ideas?
Edit: Original answer removed entirely because it wasn't actually the problem (although it did offer improvements). My answer was nearly identical to this one anyway.
After analyzing this project much more closely, the problem with the For..Next loop not returning the expected results is because the strings are being sent back and forth as byte arrays in buffers much larger than necessary (client.ReceiveBufferSize). The actual "strings" received contain large amounts of non-printable characters (garbage) added to the end to fill the buffer. The quick and dirty solution is to remove all non-printable characters:
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, _
"[^\u0020-\u007F]", String.Empty)
The whole Sub would read like this:
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, "[^\u0020-\u007F]", String.Empty)
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i As Integer = 1 To (listbox_highscores.Items.Count - 1)
tosend &= "," & listbox_highscores.Items(i).ToString
Next
SendMessage(tosend)
End If
tmr.Start()
End Sub
Try this, your comma's are off as well...
Dim tosend As String = String.Empty
Dim intCount As Integer = 0
For i As Integer = 0 To listbox.Items.Count - 1
If intCount >= 1 Then
tosend &= "," & listbox.Items(i).ToString
Else
tosend &= listbox.Items(i).ToString
intCount += 1
End If
Next
MessageBox.Show(tosend)
Screenshot THAT IT WORKS!

ThreadState always is "Unstarted"

When I start a thread, the ThreadState always is "Unstarted" even if I do a "Thread.Abort()", my thread starts and finish the work good... I don't know why I get that always the same state.
Dim thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)
thread_1.Start()
System.Threading.Thread.Sleep(100)
While not thread_1.ThreadState = Threading.ThreadState.Running
MsgBox(thread_1.ThreadState.ToString) ' "Unstarted"
thread_1.Abort()
MsgBox(thread_1.ThreadState.ToString) ' "Unstarted" again and again...
End While
UPDATE
This is the sub who calls the thread, and the problem is the "while" statament is not waiting,
PS: You can see a comment explanation at the middle of this sub:
public sub...
...
If Not playerargs = Nothing Then
If randomize.Checked = True Then
Dim thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)
thread_1.Start()
System.Threading.Thread.Sleep(50)
While thread_1.ThreadState = Threading.ThreadState.Running
Windows.Forms.Application.DoEvents()
End While
Else
progresslabel.Text = "All files added..."
End If
' HERE IS THE PROBLEM, IF I CHECK "AUTOCLOSE" CHECKBOX THEN,
' THE FORM ALWAYS TRY TO CLOSE BEFORE THREAD IS COMPLETED:
' -----------------------------------------
If autoclose.Checked = True Then Me.Close()
'------------------------------------------
Else
...
End Sub
And here is the "mithread" thread:
Public Sub mithread()
Dim Str As String
Dim Pattern As String = ControlChars.Quote
Dim ArgsArray() As String
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
Using objWriter As New System.IO.StreamWriter(Temp_file, False, System.Text.Encoding.UTF8)
Dim n As Integer = 0
Dim count As Integer = 0
Dim foldercount As Integer = -1
For Each folder In ArgsArray
foldercount += 1
If foldercount > 1 Then
InvokeControl(ProgBarPlus1, Sub(x) x.Max = foldercount)
End If
Next
If foldercount = 1 Then
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
InvokeControl(ProgBarPlus1, Sub(x) x.Max = files.Count)
For Each file In files
n += 1
CheckPrimeNumber(n)
count += 1
If file.Extension.ToLower = ".lnk" Then
Dim ShotcutTarget As String = Shortcut.ResolveShortcut((file.FullName).ToString())
objWriter.Write(ShotcutTarget & vbCrLf)
Else
objWriter.Write(file.FullName & vbCrLf)
End If
Next
End If
Next
ElseIf foldercount > 1 Then
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
InvokeControl(ProgBarPlus1, Sub(x) x.Value += 1)
For Each file In files
If file.Extension.ToLower = ".lnk" Then
Dim ShotcutTarget As String = Shortcut.ResolveShortcut((file.FullName).ToString())
objWriter.Write(ShotcutTarget & vbCrLf)
Else
objWriter.Write(file.FullName & vbCrLf)
End If
Next
End If
Next
End If
End Using
If Not thread_1.ThreadState = Threading.ThreadState.AbortRequested Then
MsgBox(thread_1.ThreadState.ToString)
Randomize_a_file.RandomizeFile(Temp_file)
InvokeControl(ProgBarPlus1, Sub(x) x.Value = 0)
' Process.Start(userSelectedPlayerFilePath, ControlChars.Quote & Temp_file.ToString() & ControlChars.Quote)
InvokeControl(progresslabel, Sub(x) x.Text = "All files launched...")
End If
End Sub
Its not easy to work out what your problem is, but i can say for sure a While Loop and DoEvents is not the way forward at all.
Instead raise an event when the thread has done all its work, subscribe to the event, and when it is raise close the form (if autoclose = true):
Public Class Form1
Public Event threadCompleted()
Public Sub New()
InitializeComponent()
AddHandler threadCompleted, AddressOf Me.Thread_Completed
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t1 As New Threading.Thread(AddressOf mithread)
t1.Start()
End Sub
Public Sub mithread()
'simulate some work:
Threading.Thread.Sleep(3000)
'then raise the event when done
RaiseEvent threadCompleted()
End Sub
Public Delegate Sub Thread_CompletedDelegate()
Private Sub Thread_Completed()
If Me.InvokeRequired Then
Me.BeginInvoke(New Thread_CompletedDelegate(AddressOf Thread_Completed))
Else
If autoclose.Checked = True Then
Me.Close()
End If
End If
End Sub
End Class
Or use a background worker which does all this, plus handles reporting progress and cancelation all for you.
Sounds like something is happening in mithread that is preventing the thread from fully starting. I ran similar code with an empty sub for mithread and I get the expected threadstate (Stopped then Aborted).
Sub Main()
Dim thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)
thread_1.Start()
System.Threading.Thread.Sleep(100)
While Not thread_1.ThreadState = Threading.ThreadState.Running
Console.WriteLine(thread_1.ThreadState.ToString)
thread_1.Abort()
Console.WriteLine(thread_1.ThreadState.ToString)
If thread_1.ThreadState = Threading.ThreadState.Aborted Then Exit While
End While
End Sub
Sub mithread()
End Sub