在播放 mp3 之前更新 C# 中的标签
我正在摆弄一个小问题。在 C# 程序中,我有一个标签,其颜色最初为黑色。播放 MP3 文件时,标签变为绿色,音乐结束后,标签的颜色应为黑色。
现在,音乐已播放,但标签未更新。我使用了几个代码示例,但它们都不起作用。我知道这与事件和调用有关,但是我必须如何更改此代码才能使其工作?在 Java 中,我使用 SwingUtilities.InvokeLater() 方法,但据我所知,在 C# 中没有对应的方法。
delegate void LabelUpdate();
private void check()
{
new Thread(new ThreadStart(updateLabel)).Start();
playSound();
next(); // Used to set the label-color to black
}
private void updateLabel()
{
if (label1.InvokeRequired)
{
UpdateBox d = new LabelUpdate(updateLabel);
this.Invoke(d);
}
else
{
label1.ForeColor = Color.Green;
}
}
非常感谢任何帮助!
I'm fiddling around with a small problem. In a C#-program, I've a label whose color initially is black. Whilst a MP3-file is played, the label gets a green color and after the end of the music, the color of the label should be black.
Now, the music is played but the label doesn't get updated. I used several code-examples, but none of them is working. I know that is has something to do with events and invocation, but how must I change this code in order to make it work? In Java I use the SwingUtilities.InvokeLater()-method, but as far as I'm aware there's no counterpart to this in C#..
delegate void LabelUpdate();
private void check()
{
new Thread(new ThreadStart(updateLabel)).Start();
playSound();
next(); // Used to set the label-color to black
}
private void updateLabel()
{
if (label1.InvokeRequired)
{
UpdateBox d = new LabelUpdate(updateLabel);
this.Invoke(d);
}
else
{
label1.ForeColor = Color.Green;
}
}
Any help is greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在颜色更改后添加
Application.DoEvents();
。在我看来,最好写这样的东西:Try to add
Application.DoEvents();
after color changing. In my opinion it would be best to write something like:我没有太多使用线程,但是要在使用一个线程时更新 GUI,您可以使用
希望这会有所帮助。
I've not used thread much but to getting the GUI to update while using one thread you can use
Hope this helps.
谢谢,那正在工作。出于测试目的,我用 Thread.Sleep(200) 替换了 wmp 对象的播放方法 - 它按预期工作。
不幸的是,如果用播放音频文件的命令替换 Thread.Sleep() 函数,这将不起作用。我假设音频文件是在单独的线程中播放的。
当然,我可以通过在 play() 方法之后添加 Thread.Sleep() 来忽略这一点,但是有更好的方法吗?
Thank you, that is working. I replaced the play-method of the wmp-object with Thread.Sleep(200), for testing purposes - it works as desired.
Unfortunately this is not working if replace the Thread.Sleep()-function with the commands to play the audio-file. I assume that the audio-file is played in a seperate thread.
Of course I could ignore this by adding Thread.Sleep() after the play()-method, but is there a better way for doing this?