Timer Class
Definition
Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.
Examples
The following example implements a simple interval timer, which sets off an alarm every five seconds. When the alarm occurs, a MessageBox displays a count of the number of times the alarm has started and prompts the user as to whether the timer should continue to run.
Remarks
A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.
This class provides methods to set the interval, and to start and stop the timer.
The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.
Constructors
Initializes a new instance of the Timer class.
Initializes a new instance of the Timer class together with the specified container.
Properties
Gets a value indicating whether the component can raise an event.
(Inherited from Component)
Gets the IContainer that contains the Component.
(Inherited from Component)
Gets a value that indicates whether the Component is currently in design mode.
(Inherited from Component)
Gets or sets whether the timer is running.
Gets the list of event handlers that are attached to this Component.
(Inherited from Component)
Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.
Gets or sets the ISite of the Component.
(Inherited from Component)
Gets or sets an arbitrary string representing some type of user state.
Methods
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Releases all resources used by the Component.
(Inherited from Component)
Disposes of the resources, other than memory, used by the timer.
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Serves as the default hash function.
(Inherited from Object)
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Returns an object that represents a service provided by the Component or by its Container.
(Inherited from Component)
Gets the Type of the current instance.
(Inherited from Object)
Obtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Creates a shallow copy of the current Object.
(Inherited from Object)
Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Raises the Tick event.
Starts the timer.
Stops the timer.
Returns a string that represents the Timer.
Events
Occurs when the component is disposed by a call to the Dispose() method.
(Inherited from Component)
Occurs when the specified timer interval has elapsed and the timer is enabled.
Timer Класс
Определение
Реализует таймер, который вызывает событие через определенные пользователем интервалы времени. Implements a timer that raises an event at user-defined intervals. Данный таймер оптимизирован для приложений формы Windows Forms и должен использоваться в окне. This timer is optimized for use in Windows Forms applications and must be used in a window.
Примеры
В следующем примере реализуется простой интервал таймера, который устанавливает сигнал каждые пять секунд. The following example implements a simple interval timer, which sets off an alarm every five seconds. При возникновении будильника MessageBox выводит количество попыток запуска сигнала и предлагает пользователю указать, следует ли продолжать выполнение таймера. When the alarm occurs, a MessageBox displays a count of the number of times the alarm has started and prompts the user as to whether the timer should continue to run.
Комментарии
Объект Timer используется для вызова события через определенные пользователем интервалы. A Timer is used to raise an event at user-defined intervals. Этот таймер Windows предназначен для среды с одним потоком, в которой потоки пользовательского интерфейса используются для обработки. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. Для этого необходимо, чтобы пользовательский код имел доступ к конвейеру сообщений пользовательского интерфейса и всегда работал из одного потока, или маршалировать вызов в другой поток. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
При использовании этого таймера используйте Tick событие для выполнения операции опроса или для отображения экрана-заставки на указанный период времени. When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Если Enabled свойство имеет значение true , а Interval свойство больше нуля, то Tick событие вызывается с интервалами в зависимости от Interval значения свойства. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.
Этот класс предоставляет методы для задания интервала, а также для запуска и завершения таймера. This class provides methods to set the interval, and to start and stop the timer.
Компонент таймера Windows Forms является однопотоковым и ограничивается точностью до 55 миллисекунд. The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. Если вам требуется многопоточный таймер с большей точностью, используйте Timer класс в System.Timers пространстве имен. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.
Конструкторы
Инициализирует новый экземпляр класса Timer. Initializes a new instance of the Timer class.
Инициализирует новый экземпляр класса Timer вместе с указанным контейнером. Initializes a new instance of the Timer class together with the specified container.
Свойства
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Возвращает или задает признак активности таймера. Gets or sets whether the timer is running.
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Возвращает или задает время в миллисекундах до вызова события Tick относительно момента, когда событие Tick произошло последний раз. Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Возвращает или задает произвольную строку, представляющую некоторый тип состояния пользователя. Gets or sets an arbitrary string representing some type of user state.
Методы
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.
(Унаследовано от Component)
Освобождает все используемые таймером ресурсы, кроме памяти. Disposes of the resources, other than memory, used by the timer.
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.
(Унаследовано от Component)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Вызывает событие Tick. Raises the Tick event.
Запускает таймер. Starts the timer.
Останавливает таймер. Stops the timer.
Возвращает строку, представляющую объект Timer. Returns a string that represents the Timer.
События
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Происходит по истечении заданного интервала таймера при условии, что таймер включен. Occurs when the specified timer interval has elapsed and the timer is enabled.
Wpf system windows forms timer
Лучший отвечающий
Вопрос
На панеле элементов для приложения Windows Forms есть элемент Timer. Для приложения WPF такого элемента нет. Как сделать таймер в приложении WPF, что бы отсчитывать нужные промежутки времени?
Ответы
В WPF есть аналог Windows Forms таймеру, который называется DispatcherTimer, он не элемент управления и создавать его нужно в коде. Посмотрите пример в описании данного таймера.
Все ответы
Создайте его в коде. Если хотите использовать тот же таймер, что и в WinForms, то:
1. Добавьте ссылку на пространство имен System.Windows.Forms
2. В нужном месте объявите любую переменную As System.Windows.Forms.Timer
3. Создайте процедуру в которой будет выполнятся код при срабатывании таймера.
4. Свяжите событие Tick таймера с помощью AddHandler с созданной ранее процедурой.
5. Настройте и запустите таймер (задайте интервал и вызовите метод Start)
Есть еще и другие таймеры, но я лично пользуюсь всегда этим.