Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to switch between photos in windows forms using time interval?

I'm having a problem while trying to switch between a group of photos in a Form(1). I'm using picturebox.Image in order to view the chosen picture, and after certain time interval (let's say 4Sec) , switch to a random photo in the same group of photos.

While switching between each photo, i would like to show another Form(2) for 1Sec, and then go back to Form(1).

my Code in Form(1):

public partial class Form1: Form
    {
        public static Timer time;
        public static Form mod;
    public Form1()
    {
        InitializeComponent();
        time = new Timer();
        mod = new Form2();

        mod.Owner = this;
        mod.Show();
        this.Hide();

        RunForm1();
    }

    public void RunForm1()
    {
        for (int i = 0; i < groupSize; i++)
        {
                mod.Owner = this;
                mod.Show();
                this.Hide();
        }
    }
}

my Code in Form(2):

public partial class Form2: Form
{
        public static Timer time;
        public int index = -1;
        public List<Image> images;
        public DirectoryInfo dI;
        public FileInfo[] fileInfos;


    public Form2()
    {
        InitializeComponent();

        images = new List<Image>();
        time = new Timer();

        dI = new DirectoryInfo(@"C:\Users\Documents\Pictures");
        fileInfos = dI.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
        foreach (FileInfo fi in fileInfos)
            images.Add(Image.FromFile(fi.FullName));

        index = images.Count;
        time.Start();

        RunForm2();
    }

    public void RunForm2()
    {
        Random rand = new Random();

        int randomCluster = rand.Next(0, 1);

        while (index != 0)
        {
            pictureBox1.Image = images[Math.Abs(index * randomCluster)];
            setTimer();
            index--;
        }
    }

    public void setTimer()
    {
        if (time.Interval == 4000)
        {
            this.Owner.Show();
            this.Close();
        }
    }

}

My main problems in this code is: 1. The time is not updating, i mean, time.Interval is always set to 100 2. i dont know why, but, the photos, never shows in the picturebox.Image although, in debug mode it shows that the photos are being selected as properly.

Thank you for you help! Roy.

like image 318
Roy Doron Avatar asked Nov 13 '22 19:11

Roy Doron


1 Answers

You need to use the Tick event from the timer to know when the time has elapsed. you check if the interval equals (==) 4000, but you need to set it to 4000 (time.Interval = 4000) and then start the timer. Then the Tick event will fire after 4 seconds. And the problem of the image not being showed could be solved by calling pictureBox1.UpdateLayout();

like image 172
Lars Stolwijk Avatar answered Nov 15 '22 08:11

Lars Stolwijk