C#:Thread.Sleep 不工作
我有一些代码,旨在显示一段时间的形式并播放声音。 但该表格保持开放状态。
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();
}
它只是保持窗体打开状态,不会关闭或隐藏。 ImageContainer是一个Form,里面有一个名为imgView的PictureBox。 我需要它在关闭之前超时 1 秒。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该行:
使表单以模态方式显示,以便该方法阻止并阻止其他所有内容运行,直到表单关闭。
将该行更改为:
This is non-modal,该方法的其余部分将完成。
The line:
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:
This is non-modal, and the rest of the method will complete.
ShowDialog() 是模态的,在关闭对话框之前永远不会返回。您想要 Show(),并且您可能想向自己发送一条计时器消息而不是睡觉。
这里有一些示例代码:
http://www.codeproject.com/KB/cs/A_Custom_Message_Box。 ASPX
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
当您调用
showdialog()
时,Sleep 永远不会被调用,该表单会导致调用线程等待,直到表单中的代码关闭窗口。使用表单中的代码关闭窗口,事情就会像您期望的那样工作。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.