Farook
Farook

Reputation: 85

Loading and viewing images from imagelist

As you see the code given below is not very useful. Is it possible to shorten the code. Mousewheel back and forward give the same result (next image). Keydown cannot be configured.

Private Sub Images_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    count += 1
    If count + 1 > ImageList1.Images.Count Then
        count = 0
    End If
    PictureBox1.Image = ImageList1.Images.Item(count)
End Sub

Private Sub Images_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseWheel
    count += 1
    If count + 1 > ImageList1.Images.Count Then
        count = 0
    End If
    PictureBox1.Image = ImageList1.Images.Item(count)
End Sub

Private Sub Images_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.Down Then
        count += 1
        If count + 1 > ImageList1.Images.Count Then
            count = 0
        End If
        PictureBox1.Image = ImageList1.Images.Item(count)
    End If
End Sub

Upvotes: 2

Views: 10420

Answers (1)

Harsh
Harsh

Reputation: 3751

Here is a way to shorten this, just use function:

Private Sub Images_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    PictureBox1.Image = ImageList1.Images.Item(increaseCount(count))
End Sub

Private Sub Images_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseWheel
If e.Delta > 0 Then
    PictureBox1.Image = ImageList1.Images.Item(decreaseCount(count))
ElseIf e.Delta < 0 Then
    PictureBox1.Image = ImageList1.Images.Item(increaseCount(count))
End If
End Sub

Private Sub Images_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.KeyCode = Keys.Down Then
   PictureBox1.Image = ImageList1.Images.Item(increaseCount(count))
End If
End Sub

Private Function increaseCount(ByRef count as integer) As Integer
    count += 1
    If count + 1 > ImageList1.Images.Count Then
        count = 0
    End If
    Return count
End Sub

Private Function decreaseCount(ByRef count as integer) As Integer
    count -= 1
    If count - 1 > ImageList1.Images.Count OR count < 0 Then
        count = 0
    End If
    Return count
End Sub

e.Delta is how much you scrolled, this is depending on the options in the control panel about mouse wheel scrolling. So we can't be sure what these values will be, but the good thing is that scrolling ups is always positive and scrolling down is negative.

Upvotes: 1

Related Questions