How do I get a value from a dynamic control? - vb.net

I've got a form with a picturecontrol (default to black bg) and I have a flowlayoutpanel underneath. On the form's load it cycles through a folder of images and creates a thumbnail (picturecontrol) inside the flowlayoutpanel. What I want to do is dynamically add a click event to let the user change the main picturecontrol image with one of the thumbnails.
Private Sub TabImageLoad()
Dim apppath As String = Application.StartupPath()
Dim strFileSize As String = ""
Dim di As New IO.DirectoryInfo(apppath + "\images")
Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
Dim fi As IO.FileInfo
For Each fi In aryFi
If fi.Extension = ".jpg" Or fi.Extension = ".jpeg" Or fi.Extension = ".gif" Or fi.Extension = ".bmp" Then
Dim temp As New PictureBox
temp.Image = Image.FromFile(di.ToString + "\" + fi.ToString)
temp.Width = 100
temp.Height = 75
temp.Name = fi.ToString
temp.Visible = True
temp.SizeMode = PictureBoxSizeMode.StretchImage
AddHandler temp.Click, AddressOf Me.temp_click
FlowLayoutPanel1.Controls.Add(temp)
End If
Next
End Sub
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
PictureBox1.Image = temp.Image
End Sub
This is my code for the sub that gets the images (note the addhandler attempt) and the sub that links to the addhandler. As you've probably guessed the addhandler doesn't work because "temp" is not declared in the temp_click sub.
Any suggestions?

The sender argument is always the control that triggered the event, in this case a PictureBox:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
PictureBox1.Image = pb.Image
End Sub

I suggest you to use:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pbDynamic as PictureBox = trycast(sender,Picturebox)
Then validate with
if pbDynamic IsNot Nothing Then
PictureBox1.Image = pbDynamic.image
end if
This way you avoid runtime errors and null pointer exceptions

Related

BackgroundWorker UI and Progress issues

So I've been fiddling with this for a while and I don't know if I'm not understanding how the BackgroundWorker works and/or I'm using it wrong or if I'm missing something.
Basically what I'm trying to do is call a BackgroundWorker from a DragDrop function where the user can drop a set of images into the form. The BackgroundWorder then copies the images to a temp location thumbnails are pulled and turned into PictureBoxes and the PictureBoxes are added to a collection. Once the BackgroundWorker is completed the function runs to add all the picture boxes to the form.
All of this is working properly except the progress. The progress function doesn't like to fire until near the end (after almost all the pictures have been copied) during this time the UI is locked (which I'm sure is why the progress function isn't firing) I just can't figure out why the UI is locking.
I've stepped through the code and the ReportProgress method is being called ever loop but the ProgressReported function isn't called until near the end.
HELP! LOL
this is the ControlClass for my copying and creating thumbnails
Imports System.ComponentModel
Imports System.IO
Namespace ThumbnailViewer
Public Class ThumbnailControl
Inherits FlowLayoutPanel
Private ImageExtensions As List(Of String) = New List(Of String) From {".JPG", ".JPE", ".BMP", ".GIF", ".PNG"}
Private tempStoragePath As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\tempPhotos"
Private WithEvents bkWPhotos As New BackgroundWorker
Public Property iThumbList As List(Of PictureBox)
Public Property sImageList As List(Of String(,))
Private PopupPrg As PopUpProgress.PopUpProgressControl
Public Sub New()
Me.AutoScroll = True
Me.AllowDrop = True
Me.DoubleBuffered = True
iThumbList = New List(Of PictureBox)()
sImageList = New List(Of String(,))()
AddHandler Me.DragDrop, AddressOf ThumbnailViewerControl_DragDrop
AddHandler Me.DragEnter, AddressOf ThumbnailViewerControl_DragEnter
If Not Directory.Exists(tempStoragePath) Then Directory.CreateDirectory(tempStoragePath)
bkWPhotos.WorkerReportsProgress = True
bkWPhotos.WorkerSupportsCancellation = True
End Sub
Public Sub BackGroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bkWPhotos.DoWork
AddImage(e.Argument)
End Sub
Public Sub BackGroundWorkder_Progress(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles bkWPhotos.ProgressChanged
PopupPrg.SetProgress(e.ProgressPercentage)
End Sub
Public Sub BackGroundWorker_Complete(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bkWPhotos.RunWorkerCompleted
For Each i As PictureBox In iThumbList
Me.Controls.Add(i)
Next
PopupPrg.Destory()
Me.Cursor = Cursors.Default
End Sub
Public Sub AddImage(ByVal files As String())
Dim fImage As Image
Dim prg As Integer = 0
For Each f As String In files
If ImageExtensions.Contains(Path.GetExtension(f).ToUpperInvariant()) Then
bkWPhotos.ReportProgress(prg)
fImage = Image.FromFile(f)
File.Copy(f, tempStoragePath & "\" & Path.GetFileName(f), True)
sImageList.Add({{tempStoragePath & "\" & Path.GetFileName(f), fImage.Size.Width, fImage.Size.Height}})
Dim t As PictureBox = MakeThumbnail(fImage)
prg = prg + 1
GC.GetTotalMemory(True)
End If
Next
End Sub
Public Function MakeThumbnail(ByVal inImage As Image) As PictureBox
Dim thumb As PictureBox = New PictureBox()
thumb.Size = ScaleImage(inImage.Size, 200)
thumb.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
thumb.SizeMode = PictureBoxSizeMode.Zoom
AddHandler thumb.MouseEnter, AddressOf thumb_MouseEnter
AddHandler thumb.MouseLeave, AddressOf thumb_MouseLeave
AddHandler thumb.DoubleClick, AddressOf thumb_DoubleClick
thumb.Image = inImage.GetThumbnailImage(thumb.Width - 2, thumb.Height - 2, Nothing, New IntPtr())
iThumbList.Add(thumb)
Return thumb
End Function
Private Sub thumb_DoubleClick(ByVal sender As Object, ByVal e As EventArgs)
Dim previewForm As Form = New Form()
Dim index As Integer = Me.Controls.GetChildIndex(CType(sender, PictureBox))
Dim img As Image = Image.FromFile(sImageList(index)(0, 0))
previewForm.FormBorderStyle = FormBorderStyle.SizableToolWindow
previewForm.MinimizeBox = False
previewForm.Size = ScaleImage(img.Size, Screen.GetWorkingArea(Me).Height / 4 * 3)
previewForm.StartPosition = FormStartPosition.CenterScreen
Dim view As PictureBox = New PictureBox()
view.Dock = DockStyle.Fill
view.Image = Image.FromFile(sImageList(index)(0, 0))
view.SizeMode = PictureBoxSizeMode.Zoom
previewForm.Controls.Add(view)
previewForm.ShowDialog()
End Sub
Private Sub thumb_MouseLeave(ByVal sender As Object, ByVal e As EventArgs)
CType(sender, PictureBox).Invalidate()
End Sub
Private Sub thumb_MouseEnter(ByVal sender As Object, ByVal e As EventArgs)
Dim rc = (CType(sender, PictureBox)).ClientRectangle
rc.Inflate(-2, -2)
ControlPaint.DrawBorder((CType(sender, PictureBox)).CreateGraphics(), (CType(sender, PictureBox)).ClientRectangle, Color.Red, ButtonBorderStyle.Solid)
ControlPaint.DrawBorder3D((CType(sender, PictureBox)).CreateGraphics(), rc, Border3DStyle.Bump)
End Sub
Private Sub ThumbnailViewerControl_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs)
If e.Data.GetDataPresent(DataFormats.FileDrop) Then e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.None
End Sub
Private Sub ThumbnailViewerControl_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs)
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
Me.Cursor = Cursors.WaitCursor
PopupPrg = New PopUpProgress.PopUpProgressControl(Me, files.Count)
bkWPhotos.RunWorkerAsync(files)
End If
End Sub
Public Function ScaleImage(ByVal oldImage As Size, ByVal TargetHeight As Integer) As Size
Dim NewHeight As Integer = TargetHeight
Dim NewWidth As Integer = NewHeight / oldImage.Height * oldImage.Width
NewHeight = NewWidth / oldImage.Width * oldImage.Height
Return New Size(NewWidth, NewHeight)
End Function
End Class
End Namespace
.... FacePalm.. I figured it out. Apparently during my testing (before I decided to use this control and a background worker, I had added another drag drop function in another area of my code that was being called first. It was taking all the dragged images and turning them into Image data types. The rest of the function was commented out which is why I didn't notice it before because I was only stepping though the classes functions not the functions in the main UI. but it makes perfect sense now, the backgroundworker and the UI function were kicking off at the same time but while the UI thread was processing the Image data typing the report progress calls were stacking up.
After removing that secondary function it works exactly as it should, UI remains fully functional Images and PictureBoxes are processed in the background and the Progressbar updates properly and remains functional as well.

Add Event to Picture Box dynamically vb.net

I'm trying to add pictureboxes dynamically in vb.net.
If i play with the vars, changing the "i" value i can add the images and the event to the last picturebox created (i can only click the last images).
But when i use the code below, it says the there's something out of boundaries ( Index outside the bounds of the matrix ).
What am i doing wrong? Tks
Imports System.IO
Public Class FormMain
Dim Path1 As String = Path.GetDirectoryName(Application.ExecutablePath) & "\Source\Images\1.png"
Dim Path2 As String = Path.GetDirectoryName(Application.ExecutablePath) & "\Source\Images\2.png"
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CreateImages()
End Sub
Dim i As Integer
Dim Logo(i) As PictureBox
Sub CreateImages()
Dim i As Integer = TextBoxNumberImages.Text
For i = 0 To i - 1
Logo(i) = New PictureBox
Logo(i).Name = "Image" + Str(i)
Panel1.Controls.Add(Logo(i))
Logo(i).Image = Image.FromFile(Path1)
Logo(i).SizeMode = PictureBoxSizeMode.StretchImage
AddHandler Logo(i).Click, AddressOf _Click
Next
End Sub
'------ADD EVENT----
Dim IsImageSelected(i) As Boolean
Private Sub _Click(ByVal sender As Object, ByVal e As EventArgs)
If IsImageSelected(i) = False Then
Logo(i).Image = Image.FromFile(Path2)
IsImageSelected(i) = True
Else
Logo(i).Image = Image.FromFile(Path1)
IsImageSelected(i) = False
End If
End Sub
----EDIT----
I just changed the var declaration to inside of the function:
Sub CreateImages()
Dim i As Integer = TextBoxNumberImages.Text
Dim Logo(i) As PictureBox
For i = 0 To i - 1
Logo(i) = New PictureBox
Logo(i).Name = "Image" + Str(i)
Panel1.Controls.Add(Logo(i))
Logo(i).Image = Image.FromFile(Path1)
Logo(i).SizeMode = PictureBoxSizeMode.StretchImage
AddHandler Logo(i).Click, AddressOf _Click
Next
End Sub
Now it creates the images the way i want, but i can't access the pictureboxes in the event. Help?
Don't use an array, use a List(Of PictureBox) instead. You could also store the selected state in the Tag() of the PictureBox. To get a reference to the PictureBox that was clicked, cast the Sender parameter. All together it would look something like this:
Private Logo As New List(Of PictureBox)
Sub CreateImages()
Dim i As Integer = TextBoxNumberImages.Text
For i = 0 To i - 1
Dim pb As New PictureBox
pb = New PictureBox
pb.Tag = False ' <-- initial not selected state
pb.Name = "Image" + Str(i)
Panel1.Controls.Add(pb)
pb.Image = Image.FromFile(Path1)
pb.SizeMode = PictureBoxSizeMode.StretchImage
AddHandler pb.Click, AddressOf _Click
Logo.Add(pb)
Next
End Sub
Private Sub _Click(ByVal sender As Object, ByVal e As EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
Dim selected As Boolean = DirectCast(pb.Tag, Boolean)
If selected = False Then
pb.Image = Image.FromFile(Path2)
Else
pb.Image = Image.FromFile(Path1)
End If
pb.Tag = Not selected ' toggle selected state
End Sub

Is there a way in VB.NET to have buttons and menu bars that are built in the code show up in the design view?

Is there a way in VB.NET to make components like buttons and menus bars show in design view of you added them in programmatically?
I now in Java i you add a button in the code it will show in design view if you switch back and forth. Can this be done in VB.NET.
Code:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'defining the main menu bar
Dim mnuBar As New MainMenu()
'defining the menu items for the main menu bar
Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")
'adding the menu items to the main menu bar
mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
' defining some sub menus
Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")
'add sub menus to the File menu
myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)
'add the main menu to the form
Me.Menu = mnuBar
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
'create a new TreeView
Dim TreeView1 As TreeView
TreeView1 = New TreeView()
TreeView1.Location = New Point(5, 30)
TreeView1.Size = New Size(150, 150)
Me.Controls.Add(TreeView1)
TreeView1.Nodes.Clear()
'Creating the root node
Dim root = New TreeNode("Application")
TreeView1.Nodes.Add(root)
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))
'Creating child nodes under the first child
For loopindex As Integer = 1 To 4
TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _
TreeNode("Sub Project" & Str(loopindex)))
Next loopindex
' creating child nodes under the root
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6"))
'creating child nodes under the created child node
For loopindex As Integer = 1 To 3
TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _
TreeNode("Project File" & Str(loopindex)))
Next loopindex
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub openInWeb()
Try
Dim url As String = "http://www.stackoverflow.com"
Process.Start(url)
Catch ex As Exception
MsgBox("There's something wrong!")
Finally
End Try
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\Users\itpr13266\Desktop\Asnreiu3.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
openInWeb()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim myStream As Stream = Nothing
Dim openFileBox As New OpenFileDialog()
openFileBox.InitialDirectory = "c:\"
openFileBox.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileBox.FilterIndex = 2
openFileBox.RestoreDirectory = True
If openFileBox.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileBox.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
'**************************
' your code will go here *
'**************************
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
Private Sub ToolTip1_Popup(sender As System.Object, e As System.Windows.Forms.PopupEventArgs) Handles ToolTip1.Popup
End Sub
Private Sub Button(p1 As Object)
Throw New NotImplementedException
End Sub
Private Function myButton() As Windows.Forms.Button
Throw New NotImplementedException
End Function
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
AboutBox1.Show()
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim lbl As New Label
lbl.Size = New System.Drawing.Size(159, 23) 'set your size (if required)
lbl.Location = New System.Drawing.Point(12, 190) 'set your location
lbl.Text = "You just clicked button 5" 'set the text for your label
Me.Controls.Add(lbl) 'add your new control to your forms control collection
End Sub
Public Sub HellowWorld()
MsgBox("Hello World!")
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
HellowWorld()
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
Dim ProgressBar1 As ProgressBar
Dim ProgressBar2 As ProgressBar
ProgressBar1 = New ProgressBar()
ProgressBar2 = New ProgressBar()
'set position
ProgressBar1.Location = New Point(10, 200)
ProgressBar2.Location = New Point(10, 250)
'set values
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 200
ProgressBar1.Value = 130
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Value = 40
'add the progress bar to the form
Me.Controls.Add(ProgressBar1)
Me.Controls.Add(ProgressBar2)
' Set the caption bar text of the form.
End Sub
End Class
The Designer does only show Controls that are created in the FormName.Designer.vb file. It does not run code in the FormName.vb file. When adding controls in the Designer, they are added to the InitializeComponent() method in the FormName.Designer.vb file.
So the only way to show the controls in the Designer is to add them in the Designer or to edit the FormName.Designer.vb file manually. If you decide for the latter, you should mimic the code that is generated by the Designer very closely in order to avoid problems when the Designer is shown. Also, be prepared that the Designer regards the FormName.Designer.vb file as completely generated code and might decide to recreate the file sooner or later omitting parts that it cannot handle.
Side note: in order to see the FormName.Designer.vb file, you should select "Show All Files" for the project in Solution Explorer.

hiding process icon to run in background

I have a programs path..like utorrent and it pid too. I have achieved these values programatically using vb.net. I just want to hide their icon form tray just to run them in background and if possible attach the process with a hotkey to call them back. Is there any way to achieve this.
Option Strict On
Option Explicit On
Option Infer Off
Imports TrayHelper
Public Class Form1
Dim x1, y1 As Single
Friend WithEvents lv As New ListView With {.Parent = Me, .Dock = DockStyle.Fill}
Private il As New ImageList
Dim nxt As Integer
Friend WithEvents mnuContextMenu As New ContextMenu() 'Moved this to be declared as global
Dim mnuItemHide As New MenuItem()
Dim mnuItemExit As New MenuItem()
Dim things As List(Of TrayButton) = TrayHelper.Tray.GetTrayButtons()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Controls.Add(lv)
lv.View = View.Details
il.ColorDepth = ColorDepth.Depth32Bit
lv.SmallImageList = il
lv.Columns.Add("Button Text", 300, HorizontalAlignment.Left)
lv.Columns.Add("PID", 50, HorizontalAlignment.Left)
lv.Columns.Add("Process Path", 600, HorizontalAlignment.Left)
'Dim things As List(Of TrayButton) = TrayHelper.Tray.GetTrayButtons()
For Each b As TrayButton In things
If b.Icon IsNot Nothing Then
il.Images.Add(b.TrayIndex.ToString, b.Icon)
Else
' When we can't find an icon, the listview will display this form's one.
' You could try to grab the icon from the process path I suppose.
il.Images.Add(b.TrayIndex.ToString, Me.Icon)
End If
Dim lvi As New ListViewItem(b.Text)
lvi.SubItems.Add(b.ProcessIdentifier.ToString)
lvi.SubItems.Add(b.ProcessPath)
lvi.ImageKey = b.TrayIndex.ToString
lv.Items.Add(lvi)
Next
lv.MultiSelect = False
'lv.ContextMenu = mnuContextMenu 'Don`t need to add if done this way
lv.FullRowSelect = True 'Added this but, you don`t need it if you don`t want it
mnuItemHide.Text = "&Hide"
mnuItemExit.Text = "&Exit"
mnuContextMenu.MenuItems.Add(mnuItemHide)
mnuContextMenu.MenuItems.Add(mnuItemExit)
AddHandler mnuItemHide.Click, AddressOf Me.menuItem1_Click
End Sub
Private Sub lv_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lv.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
If lv.GetItemAt(e.X, e.Y) IsNot Nothing Then
lv.GetItemAt(e.X, e.Y).Selected = True
mnuContextMenu.Show(lv, New Point(e.X, e.Y))
mnuItemExit.Visible = True
mnuItemHide.Visible = True
End If
End If
End Sub
Private Sub menuItem1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtValue as String
txtValue = lv.FocusedItem.SubItems(2).Text
Kill(txtValue)
Dim txtValue1 As String
txtValue1 = lv.FocusedItem.SubItems(0).Text
MessageBox.Show(txtValue1 + " has been hidden")
End Sub
End Class
this is my code
To hide your form -> form1.visible=false
To hide your form from taskbar -> form1.ShowinTaskbar=false
then go to the form1 keydown event and put this...
If e.Control And e.KeyCode = Keys.Q Then ' ---> activate with Ctrl-Q
form1.visible=true
End If

How to find and update a matching control once a file exists

I have written a WinForm project which displays a ListBox containing a list of file names. When the user clicks a submit button, the application dynamically loads and displays one PictureBox control for each file and then waits while they are processed. As PDF files are generated for each one, the matching PictureBox for that file needs to be updated to display an image.
Here's what I have so far:
Private Sub ButtonSubmit_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSubmit.Click
Dim x As Integer = 790
Dim y As Integer = 91
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim key As String = ListBox1.Items(i).ToString()
'adds picturebox for as many listbox items added
Dim MyPictureBox As New PictureBox()
MyPictureBox.Name = "pic" + key
MyPictureBox.Location = New Point(x, y)
MyPictureBox.Size = New Size(12, 12)
MyPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
Me.Controls.Add(MyPictureBox)
MyPictureBox.Image = My.Resources.Warning1
ToolTipSpooling.SetToolTip(MyPictureBox, "Creating PDF...")
x += 0
y += 13
Next i
Call CheckPDFs()
End Sub
Public Sub CheckPDFs()
Dim ListboxTicketIDs = (From i In ListBox1.Items).ToArray()
For Each Item In ListboxTicketIDs
Dim ID = Item.ToString
Dim Watcher As New FileSystemWatcher()
Watcher.Path = "C:\Temp\"
Watcher.NotifyFilter = (NotifyFilters.Attributes)
Watcher.Filter = ID + ".pdf"
AddHandler Watcher.Changed, AddressOf OnChanged
Watcher.EnableRaisingEvents = True
Next
End Sub
Private Sub OnChanged(source As Object, e As FileSystemEventArgs)
Dim p As PictureBox = CType(Me.Controls("pic" + ListBox1.Items.ToString()), PictureBox)
p.Image = My.Resources.Ok1
End Sub
I'm having trouble changing the PictureBox to a different picture once the item(s) listed in the listbox are present, based on the FileSystemWatcher. For instance, the files are not always created in the same order as they exist in the ListBox.
EDIT
Working code below.
Public Class Form1
Private WithEvents Watcher As FileSystemWatcher
Public Sub CheckPDFs()
For i As Integer = 0 To ListBox1.Items.Count - 1
Watcher = New FileSystemWatcher()
Watcher.SynchronizingObject = Me
Watcher.Path = "C:\Temp\"
Watcher.NotifyFilter = NotifyFilters.Attributes
Watcher.Filter = "*.pdf"
Watcher.EnableRaisingEvents = True
Next
End Sub
Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs) Handles Watcher.Changed
Dim key As String = Path.GetFileNameWithoutExtension(e.Name)
Dim p As PictureBox = CType(Me.Controls("pic" + key), PictureBox)
p.Image = My.Resources.Ok
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Add(TextBox1.Text)
TextBox1.Text = ""
Dim x As Integer = 5
Dim y As Integer = 5
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim key As String = ListBox1.Items(i).ToString()
'adds picturebox for as many listbox items added
Dim MyPictureBox As New PictureBox()
MyPictureBox.Name = "pic" + key
MyPictureBox.Location = New Point(x, y)
MyPictureBox.Size = New Size(15, 15)
MyPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
Me.Controls.Add(MyPictureBox)
MyPictureBox.Image = My.Resources.Info
x += 0
y += 18
Next i
Call CheckPDFs()
End Sub
First of all, you don't need to create multiple file watchers. You just need a single file watcher to watch for any changes to the folder. I would recommend declaring it as a private field at the top of your form using the WithEvents keyword so you don't have to worry about adding and removing event handlers.
Next, when the watcher raises the changed event, you can get the file name of the file that changed by looking at the properties of the event args object. You need to get the name of the file that changed and then use the file name as the key to finding the matching picture box control.
Public Class Form1
Private WithEvents Watcher As FileSystemWatcher
Public Sub CheckPDFs()
Watcher = New FileSystemWatcher()
Watcher.Path = "C:\Temp\"
Watcher.NotifyFilter = NotifyFilters.Attributes
Watcher.Filter = "*.pdf"
End Sub
Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs) Handles Watcher.Changed
Dim key As String = Path.GetFileNameWithoutExtension(e.Name)
Dim p As PictureBox = CType(Me.Controls("pic" + key), PictureBox)
p.Image = My.Resources.Ok1
End Sub
End Class
However, since you say in a comment below that the file name will not be the same as the text in the listbox, but that it will merely start with that text, you could do something like this, instead:
Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs) Handles Watcher.Changed
Dim p As PictureBox = Nothing
For Each item As Object In ListBox1.Items
If e.Name.StartsWith(item.ToString()) Then
p = CType(Me.Controls("pic" + item.ToString()), PictureBox)
Exit For
End If
Next
If p IsNot Nothing Then
p.Image = My.Resources.Ok1
End If
End Sub