Меню Рубрики

System windows forms application doevents

Функция DoEvents DoEvents function

Уступает выполнение, чтобы операционная система могла обработать другие события. Yields execution so that the operating system can process other events.

Синтаксис Syntax

DoEvents() DoEvents( )

Примечания Remarks

Функция выполнения событий DoEvents возвращает целое число, представляющее количество открытых форм в автономных версиях Visual Basic, таких как профессиональный выпуск Visual Basic. The DoEvents function returns an Integer representing the number of open forms in stand-alone versions of Visual Basic, such as Visual Basic, Professional Edition. DoEvents возвращает нуль во всех других приложениях. DoEvents returns zero in all other applications.

DoEvents передает управление операционной системе. DoEvents passes control to the operating system. Управление возвращается, когда операционная система завершает обработку событий в очереди и все ключи в очереди SendKeys отправлены. Control is returned after the operating system has finished processing the events in its queue and all keys in the SendKeys queue have been sent.

Функция DoEvents наиболее полезна для простых действий, таких как разрешение пользователю отменить процесс (например, поиск файла) после его запуска. DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. Для длительных процессов передачу процессора лучше выполнять с помощью функции Timer или передачи задачи компоненту ActiveX EXE. For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component. В последнем случае задача может продолжать полностью независимо от приложения, а операционная система отвечает за многозадачность и временной срез. In the latter case, the task can continue completely independent of your application, and the operating system takes care of multitasking and time slicing.

Временно уступая процессор в процедуре события, всегда проверяйте, чтобы процедура не выполнялась повторно из другой части вашего кода, прежде чем будет возвращен первый вызов; это может привести к непредсказуемым результатам. Any time you temporarily yield the processor within an event procedure, make sure the procedure is not executed again from a different part of your code before the first call returns; this could cause unpredictable results. Кроме того, не используйте DoEvents, если есть вероятность, что другие приложения будут взаимодействовать с вашей процедурой непредсказуемым образом в то время, на которое вы отдали управление. In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.

Пример Example

В этом примере функция DoEvents используется для вызова передачи выполнения в операционной системе один раз на каждые 1000 итераций цикла. This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. DoEvents возвращает количество открытых форм Visual Basic, но только в том случае, если ведущее приложение — Visual Basic. DoEvents returns the number of open Visual Basic forms, but only when the host application is Visual Basic.

См. также See also

Поддержка и обратная связь 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.

Источник

Application. Do Events Метод

Определение

Обрабатывает все сообщения Windows, которые в данный момент находятся в очереди сообщений. Processes all Windows messages currently in the message queue.

Примеры

В следующем примере кода демонстрируется использование DoEvents метода. The following code example demonstrates using the DoEvents method. При выполнении примера пользователь может выбрать графические файлы из OpenFileDialog . When the example runs, a user can select graphics files from an OpenFileDialog. Выбранные файлы отображаются в форме. The selected files are displayed in the form. DoEventsМетод принудительно выполняет перерисовку формы для каждого открытого графического файла. The DoEvents method forces a repaint of the form for each graphics file opened. Чтобы выполнить этот пример, вставьте следующий код в форму, содержащую PictureBox именованную PictureBox1 , OpenFileDialog именованную OpenFileDialog1 и кнопку fileButton с именем. To run this example, paste the following code in a form containing a PictureBox named PictureBox1 , an OpenFileDialog named OpenFileDialog1 , and a button named fileButton . Вызовите InitializePictureBox InitializeOpenFileDialog методы и из конструктора или Load метода формы. Call the InitializePictureBox and InitializeOpenFileDialog methods from the form’s constructor or Load method.

В Visual Studio при добавлении OpenFileDialog в форму с помощью операции перетаскивания необходимо изменить следующий InitializeOpenFileDialog метод, удалив строку, которая создает новый экземпляр OpenFileDialog . In Visual Studio, if you add an OpenFileDialog to your form by using a drag operation, you will have to modify the following InitializeOpenFileDialog method by removing the line that creates a new instance of OpenFileDialog.

В этом примере также требуется, Control.Click Button чтобы событие элемента управления и FileOk событие объекта OpenFileDialog были подключены к обработчикам событий, определенным в примере. The example also requires that the Control.Click event of the Button control and the FileOk event of the OpenFileDialog are connected to the event handlers defined in the example. При выполнении примера откройте диалоговое окно, нажав кнопку. When the example is running, display the dialog box by clicking the button.

Комментарии

При запуске формы Windows Forms создается новая форма, которая затем ожидает, пока события будут обработаны. When you run a Windows Form, it creates the new form, which then waits for events to handle. Каждый раз, когда форма обрабатывает событие, она обрабатывает весь код, связанный с этим событием. Each time the form handles an event, it processes all the code associated with that event. Все остальные события ожидают в очереди. All other events wait in the queue. Пока код обрабатывает событие, приложение не отвечает. While your code handles the event, your application does not respond. Например, окно не перерисовывается, если в верхней части перетаскивается другое окно. For example, the window does not repaint if another window is dragged on top.

При вызове DoEvents в коде приложение может управлять другими событиями. If you call DoEvents in your code, your application can handle the other events. Например, при наличии формы, добавляющей данные в ListBox и добавляя их DoEvents в код, форма перерисовывается при перетаскивании другого окна. For example, if you have a form that adds data to a ListBox and add DoEvents to your code, your form repaints when another window is dragged over it. Если удалить DoEvents из кода, форма не будет перерисовываться до завершения выполнения обработчика событий нажатия кнопки. If you remove DoEvents from your code, your form will not repaint until the click event handler of the button is finished executing. Дополнительные сведения об обмене сообщениями см. в разделе Ввод данных пользователем в Windows Forms. For more information on messaging, see User Input in Windows Forms.

В отличие от Visual Basic 6,0, DoEvents метод не вызывает Thread.Sleep метод. Unlike Visual Basic 6.0, the DoEvents method does not call the Thread.Sleep method.

Как правило, этот метод используется в цикле для обработки сообщений. Typically, you use this method in a loop to process messages.

Вызов этого метода приводит к приостановке текущего потока во время обработки всех ожидающих окон сообщений. Calling this method causes the current thread to be suspended while all waiting window messages are processed. Если сообщение вызывает срабатывание события, то могут выполняться другие области кода приложения. If a message causes an event to be triggered, then other areas of your application code may execute. Это может привести к тому, что приложение будет демонстрировать непредвиденные поведения, которые трудно отладить. This can cause your application to exhibit unexpected behaviors that are difficult to debug. При выполнении операций или вычислений, которые выполняются длительное время, часто бывает предпочтительнее выполнить эти операции в новом потоке. If you perform operations or computations that take a long time, it is often preferable to perform those operations on a new thread. Дополнительные сведения об асинхронном программировании см. в разделе модель асинхронного программирования (APM). For more information about asynchronous programming, see Asynchronous Programming Model (APM).

Источник

Application. Do Events Method

Definition

Processes all Windows messages currently in the message queue.

Examples

The following code example demonstrates using the DoEvents method. When the example runs, a user can select graphics files from an OpenFileDialog. The selected files are displayed in the form. The DoEvents method forces a repaint of the form for each graphics file opened. To run this example, paste the following code in a form containing a PictureBox named PictureBox1 , an OpenFileDialog named OpenFileDialog1 , and a button named fileButton . Call the InitializePictureBox and InitializeOpenFileDialog methods from the form’s constructor or Load method.

In Visual Studio, if you add an OpenFileDialog to your form by using a drag operation, you will have to modify the following InitializeOpenFileDialog method by removing the line that creates a new instance of OpenFileDialog.

The example also requires that the Control.Click event of the Button control and the FileOk event of the OpenFileDialog are connected to the event handlers defined in the example. When the example is running, display the dialog box by clicking the button.

Remarks

When you run a Windows Form, it creates the new form, which then waits for events to handle. Each time the form handles an event, it processes all the code associated with that event. All other events wait in the queue. While your code handles the event, your application does not respond. For example, the window does not repaint if another window is dragged on top.

If you call DoEvents in your code, your application can handle the other events. For example, if you have a form that adds data to a ListBox and add DoEvents to your code, your form repaints when another window is dragged over it. If you remove DoEvents from your code, your form will not repaint until the click event handler of the button is finished executing. For more information on messaging, see User Input in Windows Forms.

Unlike Visual Basic 6.0, the DoEvents method does not call the Thread.Sleep method.

Typically, you use this method in a loop to process messages.

Calling this method causes the current thread to be suspended while all waiting window messages are processed. If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviors that are difficult to debug. If you perform operations or computations that take a long time, it is often preferable to perform those operations on a new thread. For more information about asynchronous programming, see Asynchronous Programming Model (APM).

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • System volume information windows server 2012
  • System tweaks как оптимизировать windows 7
  • System software for windows официальный сайт
  • System software for windows как пользоваться
  • System service exception windows 10 ntfs sys