0

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!

lukew
  • 431
  • 2
  • 5
  • 15

3 Answers3

0

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;
Anton Semenov
  • 6,227
  • 5
  • 41
  • 69
0

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.

Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
0

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?

lukew
  • 431
  • 2
  • 5
  • 15
  • Does function `playSound` plays sound asynchronously? if so you always will take black label because of immediatly call of `next` – Anton Semenov Feb 27 '11 at 13:26
  • The function `playSound` plays the sound via `mciSendString` from winmm.dll - I don't know whether this function plays audio-files asynchronously. – lukew Feb 27 '11 at 14:04