开发者

C#: Thread.Sleep Not working

开发者 https://www.devze.com 2023-04-11 17:39 出处:网络
I have a bit of code which is meant to show a form for a period of time and play a sound. However the Form stays open.

I have a bit of code which is meant to show a form for a period of time and play a sound. However the Form stays open.

    static void Main(string[] args)
    {
        SoundPlayer sp = new SoundPlayer();
        ShowIm开发者_JAVA技巧age(@"Resources\Fish.png", "Fish", 256, 256, 1000);
        sp.SoundLocation = @"Resources\fish.wav";
        sp.Play();

    }


    public static void ShowImage(string img, string title, int width, int height, int timeout)
    {
        ImageContainer ic = new ImageContainer();
        ic.imgView.Image = Image.FromFile(img);
        ic.Text = title;
        ic.Size = ic.imgView.Image.Size;
        ic.Height = height;
        ic.Width = width;
        ic.ShowDialog();
        Thread.Sleep(timeout);
        ic.Hide();
        ic.Opacity = 0;
        ic.Dispose();
    }

It just stays with the form open doesn't close or hide. ImageContainer is a Form with a PictureBox called imgView in it. I need it to time out for 1 second before it closes.


The line:

ic.ShowDialog();

Causes the form to show in a modal fashion, so that method blocks and prevents everything else from running until the form closes.

Change that line to:

ic.Show();

This is non-modal, and the rest of the method will complete.


ShowDialog() is modal and never returns until you close the dialog. You want Show(), and also you probably want to send a timer message to yourself instead of sleeping.

Some sample code here:

http://www.codeproject.com/KB/cs/A_Custom_Message_Box.aspx


Sleep never gets called when you call showdialog() the form causes the calling thread to wait until the code in the form closes the window. close the window with code in your form and things will work more like you expect.

0

精彩评论

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

关注公众号