Quirk
Quirk

Reputation: 9

VB.NET PictureBox scroll through images in a folder

I have a pictureBox on my form along with two buttons (Back and Forward) but I can not find a viable method of doing what I wish to do: Scrolling through images in a folder like the default Windows Picture Viewer does with Arrow Keys.

Is there an efficient way to do this?

I'm using Visual Basic .NET with Visual Studio 2010, if that matters.

Upvotes: 0

Views: 6525

Answers (2)

steinar
steinar

Reputation: 9673

You'll need to load the pictures using DirectoryInfo, then browse through them with an index. Here is an example:

Public Class Form1
    Private files As List(Of FileInfo)
    Private currentFileIndex As Integer

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        RefreshFolder("c:\path\to\your\pictures")
    End Sub

    Private Sub backButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles backButton.Click
        Advance(-1)
        ShowCurrentFile()
    End Sub

    Private Sub forwardButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles forwardButton.Click
        Advance(1)
        ShowCurrentFile()
    End Sub

    Private Sub Advance(ByVal delta As Integer)
        currentFileIndex = ((currentFileIndex + files.Count) + delta) Mod files.Count
    End Sub

    Private Sub RefreshFolder(ByRef path As String)
        Dim di As DirectoryInfo = New DirectoryInfo(path)
        files = (From c In di.GetFiles()
                Where IsFileSupported(c)
                Select c).ToList()

        If files.Count > 0 Then
            currentFileIndex = 0
        End If

        ShowCurrentFile()
    End Sub

    Private Sub ShowCurrentFile()
        If currentFileIndex <> -1 Then
            Try
                PictureBox1.Image = Image.FromFile(files(currentFileIndex).FullName)
            Catch ex As Exception
                ' TODO: handle exceptions gracefully
                Debug.WriteLine(ex.ToString)
            End Try
        End If
    End Sub

    Private Function IsFileSupported(ByRef file As FileInfo) As Boolean
        Return file.Extension = ".jpg" Or file.Extension = ".png" ' etc
    End Function
End Class   

Upvotes: 1

Aladdin
Aladdin

Reputation: 639

you should be more specific. if it will help you you have to create two subrotines that assign the next and pervious image to the picture box and triggier these subrotines on the key down events and the bottons clicks.

Upvotes: 0

Related Questions