简体   繁体   中英

Pass an integer to a timer in WinForms application

I have my built in timer:

System.Windows.Forms.Timer timerLoop;

When the timer is started, I want (if possible) to pass this timer an integer value.

timerLoop.Start();

Till now, I only created a general variable that the timer can read and update this variable just before starting my timer.

You can do this two ways (maybe more):

Extend base Timer by creating new one that inherit it:

private class TimerExnteded : Timer
{
    public int Value { get; set; }

    public TimerExnteded(int value)
    {
        Value = value;
    }
}

and use that value in Tick event.

Use Tag property of Timer

Timer t = new Timer();
 t.Tag = 5;
 t.Start();

 //event
 private void t_Tick(object sender, EventArgs e)
 {
     var timer = sender as Timer;
     var value = (timer.Tag as int?) ?? 0; 

     value++;

     timer.Tag = value;
 }

Second approach uses boxing/unboxing of value.

您还可以使用闭包:

t.Tick += (s, a) => OnTick(YourValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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