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

标签 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 的代码,但这也不起作用...

最佳答案

我会使用 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
    }

关于c# - 如何加载图像,然后等待几秒钟,然后播放 mp3 声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2123158/

相关文章:

c# - 你能在 C# 中编写一段 C++ 代码吗?

c# - 查找另一个对象的对象的有效解决方案

c# - Windows 窗体应用程序数据库 : "An unhandled exception of type ' System. ArgumentException 发生在 System.Data.dll 中”

c# - 如何将字符串转换为具有 unix 行结尾的字节?

c# 将 System.Drawing.Graphics 保存到文件

c# - 减少动态添加控件的内存使用

c# - GIF 动画在 Windows 窗体中不起作用

C# 解析日期和时间

c# - 这可能在 C# 中完成吗?

c# - 在 Windows 窗体中操作拖放图像 C#