Windows form timer interval

Компонент Timer (Windows Forms) Timer Component (Windows Forms)

Компонент Windows Forms Timer вызывает событие через определенные интервалы времени. The Windows Forms Timer is a component that raises an event at regular intervals. Этот компонент предназначен для работы в среде Windows Forms. This component is designed for a Windows Forms environment.

в этом разделе In This Section

Общие сведения о компоненте Timer Timer Component Overview
Основные понятия, связанные с компонентом Timer, который служит для настройки отклика на периодические события в приложении. Introduces the general concepts of the Timer component, which allows you to set up your application to respond to periodic events.

Ограничения свойства Interval компонента Timer в Windows Forms Limitations of the Windows Forms Timer Component’s Interval Property
Описываются известные ограничения на интервал таймера, которые могут влиять на его применение. Describes known limitations of the timer’s interval that may affect how you can use it.

Справочник Reference

Класс System.Windows.Forms.Timer System.Windows.Forms.Timer class
Справочная информация о классе, используемом для таймеров форм Windows Forms, и его членах. Provides reference information on the class, used for Windows Forms timers, and its members.

Класс System.Timers.Timer System.Timers.Timer class
Справочная информация о классе System.Timers.Timer, используемом для серверных таймеров. Provides reference information on the System.Timers.Timer class that is used by server-based timers.

Элементы управления для использования в формах Windows Forms Controls to Use on Windows Forms
Полный список элементов управления Windows Forms со ссылками на информацию об их применении. Provides a complete list of Windows Forms controls, with links to information on their use.

Свойство Form. Тимеринтервал (Access) Form.TimerInterval property (Access)

Свойство тимеринтервал можно использовать для указания интервала (в миллисекундах) между событиями таймера в форме. You can use the TimerInterval property to specify the interval, in milliseconds, between Timer events on a form. Для чтения и записи, Long. Read/write Long.

Синтаксис Syntax

Expression. Тимеринтервал expression.TimerInterval

выражение: переменная, представляющая объект Form. expression A variable that represents a Form object.

Примечания Remarks

Значение свойства тимеринтервал — это длинное целое число от 0 до 2 147 483 647. The TimerInterval property setting is a Long Integer value between 0 and 2,147,483,647.

Это свойство можно задать с помощью таблицы свойств формы, макроса или Visual Basic. You can set this property by using the form’s property sheet, a macro, or Visual Basic.

При использовании Visual Basic свойство тимеринтервал задается в событии Load формы. When using Visual Basic, you set the TimerInterval property in the form’s Load event.

Для запуска кода Visual Basic с интервалами, указанными в свойстве тимеринтервал , добавьте код в процедуру события таймера формы. To run Visual Basic code at intervals specified by the TimerInterval property, put the code in the form’s Timer event procedure. Например, чтобы запросить записи каждые 30 секунд, поместите код для повторного запроса записей в процедуре события таймера формы, а затем присвойте свойству тимеринтервал значение 30000. For example, to requery records every 30 seconds, put the code to requery the records in the form’s Timer event procedure, and then set the TimerInterval property to 30000.

Читайте также:  Virtual machine component windows

Пример Example

В приведенном ниже примере показано, как создать мигающую кнопку в форме, отображая и скрывая значок на кнопке. The following example shows how to create a flashing button on a form by displaying and hiding an icon on the button. В процедуре события Load формы для свойства тимеринтервал формы задается значение 1000, поэтому отображение значков переключается каждую секунду. The form’s Load event procedure sets the form’s TimerInterval property to 1000 so that the icon display is toggled once every second.

Поддержка и обратная связь Support and feedback

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Ограничения свойства Interval компонента Timer в Windows Forms Limitations of the Windows Forms Timer Component’s Interval Property

Компонент Windows Forms Timer имеет Interval свойство, указывающее количество миллисекунд, прошедших между одним событием таймера и следующим. The Windows Forms Timer component has an Interval property that specifies the number of milliseconds that pass between one timer event and the next. Если компонент не отключен, таймер будет продолжать принимать Tick события с приблизительно равным интервалом времени. Unless the component is disabled, a timer continues to receive the Tick event at roughly equal intervals of time.

Этот компонент предназначен для работы в среде Windows Forms. This component is designed for a Windows Forms environment. Если вам требуется таймер, подходящий для серверной среды, см. раздел Общие сведения о серверных таймерах. If you need a timer that is suitable for a server environment, see Introduction to Server-Based Timers.

Свойство Interval The Interval Property

IntervalСвойство имеет несколько ограничений, которые следует учитывать при программировании Timer компонента: The Interval property has a few limitations to consider when you are programming a Timer component:

Если приложение или другое приложение предъявляет значительные требования к системе (например, длинные циклы, ресурсоемкие вычисления или доступ к диску, сети или портам), приложение может не получить события таймера так часто, как Interval указано в свойстве. If your application or another application is making heavy demands on the system — such as long loops, intensive calculations, or drive, network, or port access — your application may not get timer events as often as the Interval property specifies.

Не гарантируется, что интервал будет находиться в точном времени. The interval is not guaranteed to elapse exactly on time. Для обеспечения точности таймер должен проверять системные часы по мере необходимости, а не пытаться следить за накопленным временем на внутреннем уровне. To ensure accuracy, the timer should check the system clock as needed, rather than try to keep track of accumulated time internally.

Точность Interval свойства задается в миллисекундах. The precision of the Interval property is in milliseconds. Некоторые компьютеры предоставляют счетчик высокого разрешения с разрешением выше миллисекунд. Some computers provide a high-resolution counter that has a resolution higher than milliseconds. Доступность такого счетчика зависит от аппаратного процессора компьютера. The availability of such a counter depends on the processor hardware of your computer.

Читайте также:  Zabbix agent windows downloads

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) Container

Читайте также:  Какая у меня версия операционной системы windows

Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.

(Унаследовано от Component) DesignMode

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.

(Унаследовано от Component) Enabled

Возвращает или задает признак активности таймера. Gets or sets whether the timer is running.

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.

(Унаследовано от Component) Interval

Возвращает или задает время в миллисекундах до вызова события 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) Tag

Возвращает или задает произвольную строку, представляющую некоторый тип состояния пользователя. 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) Dispose()

Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.

(Унаследовано от Component) Dispose(Boolean)

Освобождает все используемые таймером ресурсы, кроме памяти. Disposes of the resources, other than memory, used by the timer.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetLifetimeService()

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetService(Type)

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.

(Унаследовано от Component) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) InitializeLifetimeService()

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

(Унаследовано от MarshalByRefObject) OnTick(EventArgs)

Вызывает событие 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) Tick

Происходит по истечении заданного интервала таймера при условии, что таймер включен. Occurs when the specified timer interval has elapsed and the timer is enabled.

Оцените статью