Moltenheim
Moltenheim

Reputation: 41

C#: Thread.Sleep Not working

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();
        ShowImage(@"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.

Upvotes: 0

Views: 450

Answers (3)

Lou Franco
Lou Franco

Reputation: 89172

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

Upvotes: 1

rerun
rerun

Reputation: 25505

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.

Upvotes: 0

CodingGorilla
CodingGorilla

Reputation: 19842

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.

Upvotes: 5

Related Questions