tags:

views:

42

answers:

4

Hi
I want to change font style of a control , for a short time. for example 2 secounds. I do like :

label1.Font = new Font(label1.Font, label1.Font.Style | FontStyle.Bold);
for(int i=0,i<4000000,i++);
label1.Font = new Font(label1.Font, label1.Font.Style | FontStyle.Regular);

but it doesn't work. what is the problem?

A: 

This is not the way to wait two seconds. Try System.Threading.Thread.Sleep(2000) instead.

As for your problem: When you say: "It doesn't work", I assume that the font stays bold instead of returning to regular. Use this instead:

FontStyle style = label1.Font.Style;
label1.Font = new Font(label1.Font, style | FontStyle.Bold); 
System.Threading.Thread.Sleep(2000)
label1.Font = new Font(label1.Font, style); 

To understand why your version did not work, look at the MSDN documentation of the Enum type.

Note that this will freeze your user interface for two seconds. You should try to avoid this. Have a look at the Timer class.

Jens
Thread.Sleep() function will freeze the form for too seconds. Its bad idea.
Stremlenye
A: 

As Jens said, a Sleep is much better than your 'busy-loop'.

a) that loop might be optimized away by the compiler
b) while busy waiting, the form can't update itself to show the first Font.

You might also need a .Refresh() just before the wait, to force the form (or just the Label) to repaint itself.

Hans Kesting
+3  A: 

What about this extension function?

public static class LabelExtensions
{
    public static Label BlinkText(this Label label, int duration)
    {
        Timer timer = new Timer();

        timer.Interval = duration;
        timer.Tick += (sender, e) =>
            {
                timer.Stop();
                label.Font = new Font(label.Font, label.Font.Style ^ FontStyle.Bold);
            };

        label.Font = new Font(label.Font, label.Font.Style | FontStyle.Bold);
        timer.Start();

        return label;
    }
}

Another interesting question comes to my mind, when writing this extension:
Does it lead to a memory leak?

Oliver
A: 

Here I answered similar question.

http://stackoverflow.com/questions/2565166/net-best-way-to-execute-a-lambda-on-ui-thread-after-a-delay/2566263#2566263

I prefer using delegates and BeginInvoke() function.

Variant with Timeris easier for understanding and has no need to access to Control from another Thread.

Stremlenye