开发者

VB.NET PictureBox scroll through images in a folder

开发者 https://www.devze.com 2023-02-17 20:26 出处:网络
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 Pi

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.


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   


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消