繁体   English   中英

在 C# 中使用计时器

[英]Using a Timer in C#

我正在尝试在 c# 中使表单在 x 时间内不可见。 有任何想法吗?

谢谢,乔恩

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;

利用封闭的快速和肮脏的解决方案。 不需要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));

在类级别做这样的事情:

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

请记住,有几种类型的计时器可用: http : //msdn.microsoft.com/en-us/magazine/cc164015.aspx

并且不要忘记在处理程序的持续时间内禁用计时器,以免您打断自己。 比较尴尬。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM