简体   繁体   中英

How to load an image, then wait a few seconds, then play a mp3 sound?

After pressing a button, I would like to show an image (using a picturebox), wait a few seconds and then play a mp3 sound, but i dont get it to work. To wait a few seconds I use System.Threading.Thread.Sleep(5000) . The problem is, the image always appears after the wait time, but I want it to show first, then wait, then play the mp3... I tried to use WaitOnLoad = true but it doesn't work, shouldn't it load the image first and the continue to read the next code line?

Here is the code I've tried (that doesn't work):

private void button1_Click(object sender, EventArgs e) {
    pictureBox1.WaitOnLoad = true;
    pictureBox1.Load("image.jpg");
    System.Threading.Thread.Sleep(5000);
    MessageBox.Show("test");//just to test, here should be the code to play the mp3
}

I also tried loading the image with "LoadAsync" and put the code to wait and play the mp3 in the "LoadCompleted" event, but that doesn't work either...

I would use the LoadCompleted event and start a timer with 5 sec interval once the image is loaded, so that the UI thread is not blocked:

   private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.WaitOnLoad = false;
        pictureBox1.LoadCompleted += new AsyncCompletedEventHandler(pictureBox1_LoadCompleted);
        pictureBox1.LoadAsync("image.jpg");
    }

    void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
    {
        //System.Timers.Timer is used as it supports multithreaded invocations
        System.Timers.Timer timer = new System.Timers.Timer(5000); 

        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

        //set this so that the timer is stopped once the elaplsed event is fired
        timer.AutoReset = false; 

        timer.Enabled = true;
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        MessageBox.Show("test"); //just to test, here should be the code to play the mp3
    }

Have you tried using Application.DoEvents(); before the wait time? I believe that should force C# to draw the image before going to sleep.

It works when application.doevents() is used.

private void button1_Click(object sender, EventArgs e) 
{
    pictureBox1.Load("image.jpg");
    Application.DoEvents();
    pictureBox1.WaitOnLoad = true;
    System.Threading.Thread.Sleep(5000);
    MessageBox.Show("test"); //just to test, here should be the code to play the mp3
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM