Search code examples
c#winformstimercustom-controlsprogrammatically-created

How to access programmatically created timer controls?


In a WinForms (C#) application I have several custom controls created at run-time. These custom controls are called JobTimers and inherit/extend the standard control Timer.

public class JobTimer : System.Windows.Forms.Timer
{
    private int IntJobID;
    public int JobID
    {
        get{return IntJobID;}
        set{IntJobID = value;}
    }
}

public static void CreateTimer(int JobID) 
{
    JobTimer ControlJobTimer = new JobTimer();
    ControlJobTimer.Enabled = true;
    ControlJobTimer.JobID = JobID;
    ControlJobTimer.Interval = 30000;
    ControlJobTimer.Tick += new EventHandler(JobTimer_Tick);
    ControlJobTimer.Start(); 
}

Similar to how we would query the collection of standard or custom controls on the Form - Can we access/query the collection of these custom JobTimer controls?

NOTE: The reason for this question to appear is that I don't see these controls getting docked/placed in any of the forms, thereby existing purely in the program's memory only. Also upon stopping/exiting the application, these controls are gone.

In other words, how does one get a list of all timers in an application along with access to their properties?


Solution

  •     public static List<JobTimer> _timers;
    
        public class JobTimer : System.Windows.Forms.Timer
        {
            private int IntJobID;
            public int JobID
            {
                get { return IntJobID; }
                set { IntJobID = value; }
            }
        }
    
        public static void CreateTimer(int JobID)
        {
            if (_timers == null)
            {
                _timers = new List<JobTimer>();
            }
            JobTimer ControlJobTimer = new JobTimer();
            ControlJobTimer.Enabled = true;
            ControlJobTimer.JobID = JobID;
            ControlJobTimer.Interval = 30000;
            ControlJobTimer.Tick += new EventHandler(JobTimer_Tick);
            ControlJobTimer.Start();
            _timers.Add(ControlJobTimer);
        }
    

    then you can access the global list _timers, all created instances of jobtimer will be added there