I have been working on a application that uses a Checkedlistbox so I can allow the user to select multiple boxes.
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
For Each item As Object In Me.CheckedListBox1.CheckedItems
Dim text As String = Me.CheckedListBox1.GetItemText(item)
Next
If text = "Line 1" Then
CreateLine1()
End If
If text = "Line 2" Then
CreateLine2()
End If
If text = "Line 3" Then
CreateLine3()
End If
If Text = "Line 4" Then
CreateLine4()
End If
If Text = "Line 5" Then
CreateLine5()
End If
It goes all the way to "Line 10". When the app runs it use cmd.exe to connect to telnet and send commands. If I have Line 1 and Line 2 selected Line 1 has no problems, but when Line 2 run it opens a cmd does, nothing for a few seconds, open another cmd, and run just the commands while not connected to the telnet. Several more widows open afterwords and the four or fifth window connected to telnet.
How can I make it so if one line if selected after it has run telnet it separates out that line as "Has been ran" before going to the next line to avoid my problem.
Addition info:
This app has a select-all and deselect-all buttons so I can not have anything that will interfere with them.
I have try using socket to replace cmd.exe.....it did not go so well and I will pass on it.
Each sub the lines go to it basically the same except to the IP address and a few commands.
I hope the original code you posted isn't actually what you're using...it doesn't seem quite right.
Perhaps something like this might be more useful:
Imports System.Reflection
Public Class Form1
Private Methods As New List(Of MethodInfo)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim MI As MethodInfo
For i As Integer = 1 To 10
mi = Me.GetType.GetMethod("CreateLine" & i, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public)
If Not IsNothing(MI) Then
Methods.Add(MI)
End If
Next
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
For Each Index As Integer In Me.CheckedListBox1.CheckedIndices
Methods(Index).Invoke(Me, Nothing)
Next
End Sub
Private Sub CreateLine1()
Debug.Print("CreateLine1()")
End Sub
Private Sub CreateLine2()
Debug.Print("CreateLine2()")
End Sub
Private Sub CreateLine3()
Debug.Print("CreateLine3()")
End Sub
Private Sub CreateLine4()
Debug.Print("CreateLine4()")
End Sub
Private Sub CreateLine5()
Debug.Print("CreateLine5()")
End Sub
Private Sub CreateLine6()
Debug.Print("CreateLine6()")
End Sub
Private Sub CreateLine7()
Debug.Print("CreateLine7()")
End Sub
Private Sub CreateLine8()
Debug.Print("CreateLine8()")
End Sub
Private Sub CreateLine9()
Debug.Print("CreateLine9()")
End Sub
Private Sub CreateLine10()
Debug.Print("CreateLine10()")
End Sub
End Class
There are lots of other ways to do this as well...
Related
I'm learning for vb.net step by step. I have two forms and I would like to make a code that is, when I click Button1 which is in the other form, then my main sub exit. I have already searched in google, but I didn't find anything. How can I solve that line?
Public Class Form1
Public Sub Main()
Form2.ShowDialog()
If Form2.Button1_Click = True then '**This line is what I stucked**
Exit Sub
End if
End Sub
End Class
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
An example using DialogResult.
In Form1:
If Form2.ShowDialog = DialogResult.OK Then
' ... do something in here ...
End If
In Form2:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.DialogResult = DialogResult.OK
End Sub
Note that if the user cancels the Form2 dialog without hitting the button then you'll get a result of Cancel back instead.
I'm coding an Anti-Virus at the moment, so it's been very complicated to code it and design it. Anyway, the other day I ran into a problem, where my ListBox is not displaying all the files that are in the selected drive/directory.
I'll put some code and images so you get the idea.
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
ListBox1.Items.Clear()
ListBox3.Items.Clear()
FolderBrowserDialog1.SelectedPath = Path.GetPathRoot(Environment.SystemDirectory) & "Boot\"
On Error Resume Next
For Each strDir As String In System.IO.Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)
For Each strFile As String In System.IO.Directory.GetFiles(strDir)
ListBox1.Items.Add(strFile)
ListBox3.Items.Add(strFile)
Next
Next
Timer1.Start()
End Sub
However, instead of the files appearing in the ListBox (ListBox3), it just gives a black screen. Maybe I should remove the TabControl that it is surrounded by?
See how it's black? It even happens when I run it.
Hope this helps! Comment if you need more information.
You may want to simplify your events by creating subs and standardizing the code instead of embedding it directly into the button click. I have created a working example of how to load directories and files dynamically.
I would also recommend doing a isolated experiment, you can easily throw together a test project to isolate the directories in question and the layout you are trying to achieve. It could be that there are other events causing noise in your debugging.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_dirs(ListBox2, "H:\")
End Sub
Sub load_files(LB As ListBox,
IO_dir As String)
Dim Files_ = IO.Directory.GetFiles(IO_dir)
With LB.Items
.Clear()
.AddRange(Files_)
End With
End Sub
Sub load_dirs(LB As ListBox,
IO_dir As String)
Dim dir_ = IO.Directory.GetDirectories(IO_dir)
With LB.Items
.Clear()
.AddRange(dir_)
End With
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
Try
Dim lb As ListBox = sender
load_files(ListBox1, lb.SelectedItem)
Catch ex As Exception
End Try
End Sub
End Class
The goal is that the form should still be clickable while the code runs (mainly to be able to break the code) AND keeps getting updated by the running code at the same time. First part works, not the second part.
Public Class FormMain
Public PleaseStopAll As Boolean
Private Sub BreakCode_Click(sender As Object, e As EventArgs) Handles BreakCode.Click
PleaseStopAll = True
End Sub
Private Sub Testeur_Click(sender As Object, e As EventArgs) Handles Testeur.Click
PleaseStopAll = False
ThreadPool.QueueUserWorkItem(AddressOf LaunchTask, 0)
End Sub
Sub LaunchTask(o As Object)
TheTask(Me)
End Sub
Public Sub ShowSomeMessage(msg As String
Me.Displayer.text = msg
End Sub
End Class
Module TaskDoer
Sub TheTask(MyMenu As FormMain)
For i As Integer = 0 To 42
whatever() 'some tasks that cannot be interrupted safely
MyMenu.ShowSomeMessage("task #" & CStr(i) & " over") ' Here is the error
If MyMenu.PleaseStopAll Then Exit For
Next
End Sub
End Module
The "status update" line tells that this task cannot interact with its parent task.
If I remove this line, the code runs just fine : code breaks when I ask to, and form remains clickable.
I tried with BackgroundWorker, but it needs actual progression to report something with ReportProgress (in increasing %) do I cannot just give a status (as string)
Pass anything else via a variable or structure
BackgroundWorker1.WorkerReportsProgress = True '<Make sure this is set
BackgroundWorker1.RunWorkerAsync()
Private SomeStatus As String
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
SomeStatus = "Hello"
BackgroundWorker1.ReportProgress(0)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ShowSOmeMEssage(SomeStatus)
End Sub
FYI: The progress thing is only so you can call a routine on the main UI thread. You can set as many thread-safe variables as you want on the form from within the backgroundworker. It's just updating the UI that's bothersome, though there is a workaround for that too.
Im trying to figure out how to run through even numbers on a for loop and then print those numbers to a label in a windows form via a button. Currently, when I press the button it only displays 20. I believe the code is running through the loop and then when it gets to 20 it just prints 20. I need to print all the numbers in the label object.
Heres the current code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
For intEven = 2 To 20 Step 2
lblEven.Text = intEven
Next
End Sub
End Class
Heres a picture of the application when its ran:
Running the application
And I have just figured it out!
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
Dim intEven As Integer
For intEven = 2 To 20 Step 2
lblEven.Text = lblEven.Text &
intEven.ToString & ControlChars.NewLine
Next intEven
End Sub
End Class
I need a little (or big) help with my form: I need to use everything inside the "Organize function" region in a separate thread.
I press a button in my form's "Start button" region to call the first sub of the "Organize function" subs; the first sub calls the second sub and the second sub calls the third sub.
I tried adding the third sub into a separate thread by myself and then using the second sub to pass the argument to the thread but all I've done is wrong.
Can someone please help me do this?
PS: I've deleted the non-important parts in this form to let you check better.
Thank you for reading.
Public Class Form1
#Region "Declarations"
' MediaInfo
Dim MI As MediaInfo
' Thread
Dim paused As Boolean = False
' Others
Dim NameOfDirectory As String = Nothing
Dim aFile As FileInfo
#End Region
'thread
Dim t As New Thread(AddressOf ThreadProc)
Public Sub ThreadProc()
' Aqui deberÃa ir todo el sub de "organize function", bueno... son 3 subs!
If paused = True Then MsgBox("THREAD PAUSADO")
End Sub
#Region "Properties"
...
#End Region
#Region "Load / Close"
...
#End Region
#Region "Get Total files Function"
...
#End Region
#Region "Option checkboxes"
...
#End Region
#Region "Folder buttons"
...
#End Region
#Region "Append text function"
...
#End Region
#Region "Action buttons"
' pause button
Private Sub pause_button_Click(sender As Object, e As EventArgs) Handles pause_button.Click
paused = True
End Sub
' start button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles start_button.Click
t.Start()
' Organization process
NameOfDirectory = userSelectedFolderPath
MediaInfo(NameOfDirectory)
End Sub
#End region
#Region "Organize function"
Public Sub MediaInfo(Directory)
Dim MyDirectory As DirectoryInfo
MyDirectory = New DirectoryInfo(NameOfDirectory)
MediaInfoWorkWithDirectory(MyDirectory)
End Sub
Public Sub MediaInfoWorkWithDirectory(ByVal aDir As DirectoryInfo)
Dim nextDir As DirectoryInfo
MediaInfoWorkWithFilesInDir(aDir)
For Each nextDir In aDir.GetDirectories
Using writer As StreamWriter = New StreamWriter(aDir.FullName & "\" & nextDir.Name & "\" & nextDir.Name & ".m3u", False, System.Text.Encoding.UTF8)
'overwrite existing playlist
End Using
MediaInfoWorkWithDirectory(nextDir)
Next
End Sub
Public Sub MediaInfoWorkWithFilesInDir(ByVal aDir As DirectoryInfo)
Dim aFile As FileInfo
For Each aFile In aDir.GetFiles()
' hacer cosas con aFile ...
Next
End Sub
#End Region
End Class
There is a Windows Forms component called BackgroundWorker that is designed specifically to offload long-running tasks from the UI thread to a background thread, leaving your form nice and responsive.
The BackgroundWorker component has an event called DoWork that is used to execute code on a separate thread. Drag the BackgroundWorker component onto your form and then do something like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles start_button.Click
NameOfDirectory = userSelectedFolderPath
backgroundWorker1.RunWorkerAsync(NameOfDirectory)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim directoryName as string = e.Argument
MediaInfo(directoryName)
End Sub
A couple of links that might be useful are the MSDN BackgroundWorker page and an example on Code Project.
HTH
There are around 5 dozen ways to solve the problem. I will show just 3 of them:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' fire and forget:
Task.Run(Sub() FooA()).ContinueWith(Sub() FooB()).ContinueWith(Sub() FooC())
Console.WriteLine("Button1 done")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' fire and forget:
Task.Run(Sub()
FooA()
FooB()
FooC()
End Sub)
Console.WriteLine("Button2 done")
End Sub
Private Async Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
' wait but dont block:
Await Task.Run(Sub()
FooA()
FooB()
FooC()
End Sub)
Console.WriteLine("Button3 done")
End Sub
Private Sub FooA()
Threading.Thread.Sleep(1000)
Console.WriteLine("A")
End Sub
Private Sub FooB()
Threading.Thread.Sleep(1000)
Console.WriteLine("B")
End Sub
Private Sub FooC()
Threading.Thread.Sleep(1000)
Console.WriteLine("C")
End Sub
End Class
I would suggest the one with Await (IF FW 4.x and VS2012 is not an issue).