开发者

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

开发者 https://www.devze.com 2022-12-17 02:56 出处:网络
After pressing a button, I would like to show an image (using apicturebox), wait a few seconds and then play a

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?

开发者_StackOverflowHere 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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消