Prock
Prock

Reputation: 460

PictureBox Image Won't Update/Refresh

I have an application that has a listbox, and a picture box. What I need is for when the ListBox.IndexChanged event is struck, the PictureBox image needs to update or refresh.

EDIT: The first time I select something from the list, the image loads up, but when I select another item, the image doesnt update.

I have tried both with no luck:

PictureBox1.Refresh();
PictureBox1.Update();

In the background, when the ListBox1's Index is Changed I have a script running to go to a specific web page and take a screenshot depending on which item is selected in the ListBox and replace the current imageBox's image. I was thinking that maybe I just wasnt giving it time to go and get the image, so I tried this as well with no luck:

System.Threading.Thread.Sleep(3000);

Here is what the application looks like:

enter image description here

Here is what is on the ListBox1.IndexChanged event:

Process myProcess;
myProcess = Process.Start("C:/users/bnickerson/desktop/script/RegScript.cmd");
System.Threading.Thread.Sleep(5000);
myProcess.Close();
string imgLoc = "C:/users/bnickerson/Desktop/script/result/last.png";
pictureBox1.Image = Image.FromFile(imgLoc);
pictureBox1.Update();

Upvotes: 1

Views: 9525

Answers (2)

DarrenMB
DarrenMB

Reputation: 2380

I had a similar issue where the image would not refresh to anew image regardless of methods called to try to force it.

For some reason only happened when the PictureBox was not set to "Dock:FILL"

My fix was to both dispose the image and to assign it to NULL and then apply the new cloned image as shown below.

Public Sub ApplyLastImage()
    If ScreenPicture.Image IsNot Nothing Then
        ScreenPicture.Image.Dispose()
        ScreenPicture.Image = Nothing
    End If
    ScreenPicture.Image = CType(LastImage.Clone, Drawing.Image)
    ScreenPicture.Update()
End Sub

Upvotes: 0

W0lfw00ds
W0lfw00ds

Reputation: 2106

As Hans pointed out, the image file is locked until the returned Image-object is Disposed. Try this:

using (Process ExternalProcess = new Process())
{
   ExternalProcess.StartInfo.FileName = @"C:\users\bnickerson\desktop\script\RegScript.cmd";
   ExternalProcess.Start();
   ExternalProcess.WaitForExit();
}

string imgLoc = @"C:\users\bnickerson\Desktop\script\result\last.png";
if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); }
using (Image myImage = Image.FromFile(imgLoc))
{
   pictureBox1.Image = (Image)myImage.Clone();
   pictureBox1.Update();
}

Upvotes: 2

Related Questions