如何加载图像,然后等待几秒钟,然后播放mp3声音?

时间:2010-01-23 12:43:52

标签: c# picturebox

按下按钮后,我想显示图像(使用图片框),等待几秒然后播放 mp3声音,但我不能让它工作。要等几秒钟,我会使用System.Threading.Thread.Sleep(5000)。问题是,图像总是在等待时间之后出现,但是我希望它首先显示,然后等待,然后播放mp3 ...我尝试使用WaitOnLoad = true但它没有不工作,不应该首先加载图像并继续读取下一个代码行吗?

以下是我尝试过的代码(不起作用):

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
}

我还尝试使用“LoadAsync”加载图像并将代码放在等待并在“LoadCompleted”事件中播放mp3,但这也不起作用...

3 个答案:

答案 0 :(得分:6)

我会使用LoadCompleted事件并在加载图像后以5秒的间隔启动一个计时器,这样就不会阻止UI线程:

   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
    }

答案 1 :(得分:3)

您是否在等待时间之前尝试使用Application.DoEvents();?我认为应该强迫C#在进入睡眠状态之前绘制图像

答案 2 :(得分:2)

使用application.doevents()时有效。

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
}