user2345529
user2345529

Reputation: 21

Force unseen PictureBox to load image

I have a form on which many PictureBoxes line up, not all of them are shown on the form at the same time (there's scrollbar on the form to reveal unseen PictureBoxes). Their images location are internet URLs. I want to save those images locally right after each image is loaded, therefore I hook to the ContentLoaded Event of those PictureBoxes.

The problem is that the unseen PictureBoxes do not load images, and therefore their images cannot be saved, until the form is scrolled to make them visible. But I cannot expect user will scroll the whole content of the form all the times.

Is there a way to force unseen PictureBox to load its image?

Thanks.

EDIT:

Hello, DmitryG, may be the problem is that I have my PictureBoxes LoadAsync "loading images" before loading the true content. In your code, if you add

        pb.ImageLocation = "http://images.google.com.vn/intl/en_ALL/images/logos/images_logo_lg.gif";

        pb.LoadAsync();

in the loop before

        pb.ImageLocation ="https://www.google.com/images/srpr/logo4w.png";
        pb.LoadAsync();

then load the form, you will see 7 messageboxes only instead of 10. It is because 3 PictureBoxes are hidden.

Upvotes: 2

Views: 2225

Answers (1)

DmitryG
DmitryG

Reputation: 17850

You can perform image loading despite of the picturebox visibility by calling the PictureBox.LoadAsync method. When the image loading will be completed the PictureBox.LoadCompleted will be raised:

pictureBox1.LoadCompleted += pictureBox1_LoadCompleted;

pictureBox1.InitialImage = Image.FromFile(@"... path to waiting-to-load image ...");

pictureBox1.ImageLocation = <...path to image...>;
pictureBox1.LoadAsync(); // perform loading

void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e) {
    // do something with loaded image
}

Update: sample code for auto-scroll panel and 5 pictureboxes.

panel1.AutoScroll = true;
panel1.Height = 1000;
for(int i = 0; i < 5; i++) {
    PictureBox pb = new PictureBox();
    pb.Dock = DockStyle.Top;
    pb.Height = panel1.Height/2;
    pb.WaitOnLoad = false;
    pb.InitialImage = Image.FromFile("WaitingToLoad.gif");
    pb.ImageLocation = @"https://www.google.com/images/srpr/logo4w.png";
    pb.LoadCompleted += pb_LoadCompleted;

    pb.Parent = panel1;
    pb.LoadAsync(); //<<<<<
}
//
void pb_LoadCompleted(object sender, AsyncCompletedEventArgs e) {
    MessageBox.Show("Load completed!");
}

Upvotes: 2

Related Questions