dino dino - 3 months ago 49
Vb.net Question

VB.NET How can I check if an image from my resources is loaded in a PictureBox?

I am trying to make a PictureBox change the image when pressed, and if pressed again it will change to the original image. How can I do that? Here is my code.

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
If (PictureBox1.Image = WindowsApplication1.My.Resources.Resources.asd) Then
PictureBox1.Image = WindowsApplication1.My.Resources.Resources._stop()
Else
PictureBox1.Image = WindowsApplication1.My.Resources.Resources.asd()
End If
End Sub


When I run it, it gives the following error:


Operator '=' is not defined for types "Image" and "Bitmap".


Answer

Well, it is the good kind of problem to have. There is a massive bear trap hidden in the My.Resources property getters, every time you use it you get a new bitmap object. That has many consequences, bitmaps are very expensive objects and calling their Dispose() method is very important to prevent your program from running out of memory. And comparing will always fail since it is new object. The difference between Image and Bitmap is just a minor problem.

It is crucial to use the bitmap object just once. Like this:

Private asd As Image = My.Resources.asd
Private _stop As Image = My.Resources._stop

Now you can correctly write this code since you are comparing objects for reference identity:

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    If PictureBox1.Image = asd Then
        PictureBox1.Image = _stop
    Else
        PictureBox1.Image = asd
    End If
End Sub

And like a good programmer you dispose the image objects when you no longer use them:

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    asd.Dispose()
    _stop.Dispose()
End Sub

Also fix the code that first assigns the PictureBox1.Image property, we can't see it.