Update a label in C# ere mp3 is played

179 views Asked by At

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!

3

There are 3 answers

0
Anton Semenov On BEST ANSWER

Try to add Application.DoEvents(); after color changing. In my opinion it would be best to write something like:

    label1.ForeColor = Color.Green;
    Application.DoEvents();
    playSound();
    label1.ForeColor = Color.Black;
0
Ash Burlaczenko On

I've not used thread much but to getting the GUI to update while using one thread you can use

Application.DoEvents();

Hope this helps.

2
lukew On

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?