7

I'm trying to make a form invisible for x amount of time in c#. Any ideas?

4 Answers 4

16

BFree has posted similar code in the time it took me to test this, but here's my attempt:

this.Hide();
var t = new System.Windows.Forms.Timer
{
    Interval = 3000 // however long you want to hide for
};
t.Tick += (x, y) => { t.Enabled = false; this.Show(); };
t.Enabled = true;
Sign up to request clarification or add additional context in comments.

2 Comments

Timers implement IDisposable, you should be calling it.
I suppose you could call Dispose() manually from within the event handler, but you couldn't wrap it in a using() block or the timer would be disposed before it got a chance to fire, three seconds later.
8

Quick and dirty solution taking advantage of closures. No Timer required!

private void Invisibilize(TimeSpan Duration)
    {
        (new System.Threading.Thread(() => { 
            this.Invoke(new MethodInvoker(this.Hide));
            System.Threading.Thread.Sleep(Duration); 
            this.Invoke(new MethodInvoker(this.Show)); 
            })).Start();
    }

Example:

// Makes form invisible for 5 seconds.

Invisibilize(new TimeSpan(0, 0, 5));

Comments

3

At the class level do something like this:

Timer timer = new Timer();
private int counter = 0;

In the constructor do this:

        public Form1()
        {
            InitializeComponent();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer_Tick);
        }

Then your event handler:

void timer_Tick(object sender, EventArgs e)
        {
            counter++;
            if (counter == 5) //or whatever amount of time you want it to be invisible
            {
                this.Visible = true;
                timer.Stop();
                counter = 0;
            }
        }

Then wherever you want to make it invisible (I'll demonstrate here on a button click):

 private void button2_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            timer.Start();
        }

Comments

1

Bear in mind there are several types of timers available: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

And don't forget to disable the timer for the duration of the handler, lest you interrupt your self. Rather embarrassing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.