在C#中使用计时器

7

我正在尝试在c#中让一个表单在x时间内不可见。 有什么想法吗?

谢谢, Jon

4个回答

16
在我测试这个代码的时间里,BFree已经发布了类似的代码,但是这是我的尝试:
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;

比我的方法更加简洁。+1 - BFree
计时器实现了IDisposable接口,你应该调用它。 - ctacke
我想你可以在事件处理程序内手动调用Dispose()方法,但你不能将其包装在using()块中,否则计时器将在三秒后触发之前被处理。 - Matt Hamilton

8

利用闭包实现快速而简单的解决方案。无需使用 Timer

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();
    }

示例:

// Makes form invisible for 5 seconds.

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

3
在类级别上,可以这样做:
Timer timer = new Timer();
private int counter = 0;

在构造函数中执行以下操作:
        public Form1()
        {
            InitializeComponent();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer_Tick);
        }

然后是您的事件处理程序:
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;
            }
        }

然后,在您想将其隐藏的任何位置(我将在此处演示按钮单击):

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

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接