I have a quick question, I have been struggling with something that should, in theory be quite simple.
I want to create a dynamic button out of a picture box in Visual Studio 2012, one that changes the image each time I click it.
if (pictureBox4.BackgroundImage == MyProject.Properties.Resources._1)
pictureBox4.BackgroundImage = MyProject.Properties.Resources._2;
else if (pictureBox4.BackgroundImage == MyProject.Properties.Resources._2)
pictureBox4.BackgroundImage = MyProject.Properties.Resources._1;
Now, this didn't really work fine. It wouldn't detect the image that is being currently displayed and enter the if
statement. So, instead, I've tested it this way.
int b = 1;
if (b == 1)
{
pictureBox4.BackgroundImage = MyProject.Properties.Resources._2;
b = 2;
}
if (b == 2)
{
pictureBox4.BackgroundImage = MyProject.Properties.Resources._1;
b = 1;
}
Close... but no cigar. When I click it the image does change, but just once; if I click it again, it stays the same...
So... what now? Thanks for your answers.
You're using the same image in both if clauses (Resources._2)?
Also, as TaW pointed out, when b == 1 you set b = 2 and check if b == 2. Both if clauses will be true. The second if should be an "else if"
if (b == 1)
{
pictureBox4.BackgroundImage = MyProject.Properties.Resources._2;
b = 2;
}
else if (b == 2)
{
pictureBox4.BackgroundImage = MyProject.Properties.Resources._1;
b = 1;
}
Of course you could just use an else clause:
if (b == 1)
{
pictureBox4.BackgroundImage = MyProject.Properties.Resources._2;
b = 2;
}
else
{
pictureBox4.BackgroundImage = MyProject.Properties.Resources._1;
b = 1;
}
Or if you don't want the integer variable then you could try this:
1) Pull the images from the resource just once and them in a static member.
private static readonly Image Image1 = MyProject.Properties.Resources._1;
private static readonly Image Image2 = MyProject.Properties.Resources._2;
2) Change your conditions to use the static copies instead of the resource properties (which return a new object each time).
if (pictureBox4.BackgroundImage == Image2)
{
pictureBox4.BackgroundImage = Image1;
}
else
{
pictureBox4.BackgroundImage = Image2;
}
Here is my solution for the task: In MyProject
I have a resource file called Resource1
and six Images
from called _0
to _5
:
int index = 0;
private void anImageButton_Click(object sender, EventArgs e)
{
index = (index + 1) % 6;
anImageButton.Image =
(Bitmap)MyProject.Resource1.ResourceManager.GetObject("_" + index);
}
Instead of a PictureBox
I use a simple Button anImageButton
, but it will work with your PictureBox
as well..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.